I have a c++ host in which I use tolua++ to expose some classes to Lua. One of the classes has a function that should register a callback from lua. So when the C++ code needs to call a Lua registered function it can. The function is however a table/class function. I've done this before with the string function name (not part of a lua "class") with success but I'm curious if I'm able to somehow store the Lua function and not function name.
I define my lua classes like:
MyClass = {}
function MyClass:Create()
local obj = {}
-- copy all functions from MyClass table to this local obj and return it
local k,v
for k,v in pairs(obj) do
obj[k] = v
end
return obj
end
function MyClass:Enter()
self.CPlusClass = CPlusClass:Create() -- this is the C++ class creation, I defined a static function Create()
self.CPlusClass:RegisterCallback(15, self.Callback) -- this is where I want to pass this instances function to be called back from the C++ class
end
function MyClass:Callback(reader)
-- I want to be able to use self here as well so it needs to be the same instance
end
Inside the MyClass:Enter() is where I want to register the lua "class" function MyClass::Callback to be able to be called from the C++ object. How would I pass this into a C++ function? What would the type be so that it will call MyClass:Callback() from C++ also passing in "self" so that it's the same "instance" of the class?
So I know 'self' is referring to an actual variable that I created and I assume will be in the global table by variable name, but when you are inside the lua "class" how can I tell what variable name 'self' is referring too? If I could get that I could pass that to my C++ function and store it as a string so that I can call getglobal on it to get that specific table, and then I could also pass the table function name as string and in C++ I could get that also, and call it. But the question would be, how can I convert 'self' to the actual variable name it's pointing too so I can call getglobal in C++ to get that table?
self
is not a global, self is an automatic variable defined by thetable:function
syntactic sugar.function table:class(args...) ... end
is identical tofunction table.class(self, args...) ... end
. Similarly a call totab:class(args...)
is identical totab.class(tab, args...)
(though tab is evaluated only once). – Etan Reisnerself
is the variable name. It is the first argument to the function. It is the table on which the function is called. – Etan Reisner