使用Luabind实例化lua类
Instantiate lua classes using Luabind
是否可以使用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。
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");
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 为什么 gcc 和 clang 为函数模板的实例化生成不同的符号名称?
- 检查某些类型是否是模板类 std::optional 的实例化
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 模板化类构造函数的模板实例化
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何推动在LUA脚本上使用的现有/创建/实例化类对象
- Lua到c++,用于实体修改的实例化函数
- 使用Luabind实例化lua类