使用Luabind实例化lua类

Instantiate lua classes using Luabind

本文关键字:lua 实例化 Luabind 使用      更新时间:2023-10-16

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

class "Person"
function Person:__init(name)
    self.name = name
end
function Person:display()
    print(self.name)
end

我可以在同一个Lua脚本中实例化这个类,一切都很好。但是,我想在我的c++应用程序中使用Luabind从这个类实例化一个新对象。我尝试了以下操作:

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

我希望看到"John Doe"输出到控制台。相反,我看到了一个Lua运行时错误。创建新对象的调用似乎有效。问题似乎是self在显示功能中为nil。

selfnil,因为如果你在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");