使用Luabind实例化Lua类

是否可以在 C++ 应用程序中使用 Luabind 实例化 Lua "类"?为了说明问题,考虑以下简单的 Lua 脚本:

class "Person"

function Person:__init(name)
    self.name = name
end

function Person:display()
    print(self.name)
end

我可以在同一个 Lua 脚本中实例化这个类,并且一切都运行良好。然而,我想使用 Luabind 从我的 C++ 应用程序中实例化这个类的一个新对象。我尝试了以下操作:

luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
myObject["display"]();

我期望在控制台看到输出 "John Doe"。但是,我得到了一个 Lua 运行时错误。创建新对象的调用似乎有效。问题似乎是 display 函数中的 self 是 nil。

点赞
用户2107136
用户2107136

self 是 _nil_,因为在 lua 中使用“:”运算符时,lua 将自动将调用者作为第一个参数提供。 所以:

somePerson:display() == somePerson.display(somePerson)

因此,您也需要提供此 self-argument:

luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
myObject["display"](myObject);

或更好的是:使用 luabind 中为此目的提供的简单函数

luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
luabind::call_member<void>(myObject, "display");
2014-06-20 09:51:10