Is it possible to instantiate Lua "classes" using Luabind from a c++ application? To illustrate the problem, consider the following simple Lua script:
class "Person"
function Person:__init(name)
self.name = name
end
function Person:display()
print(self.name)
end
I can instantiate this class in the same Lua script and everything works fine. However, I want to instantiate a new object from this class using Luabind from within my c++ application. I have tried the following:
luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
myObject["display"]();
I would expect to see "John Doe" output to the console. Instead, I am greeted with a Lua runtime error. The call to create the new object seemingly works. The problem appears to be that self
, in the display function, is nil.
self is nil because if you use the ":"-operator in lua, then lua will automatically provide the caller as first argument. so:
somePerson:display() == somePerson.display(somePerson)
Therefore you need to provide that self-argument too:
luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
myObject["display"](myObject);
Or even better: Use the simple functions in luabind available for that purpose
luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
luabind::call_member<void>(myObject, "display");