简体   繁体   English

使用Luabind实例化lua类

[英]Instantiate lua classes using Luabind

Is it possible to instantiate Lua "classes" using Luabind from a c++ application? 是否可以在C ++应用程序中使用Luabind实例化Lua“类”? To illustrate the problem, consider the following simple Lua script: 为了说明此问题,请考虑以下简单的Lua脚本:

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. 我可以在相同的Lua脚本中实例化此类,并且一切正常。 However, I want to instantiate a new object from this class using Luabind from within my c++ application. 但是,我想在我的c ++应用程序中使用Luabind从该类实例化一个新对象。 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. 我希望看到“ John Doe”输出到控制台。 Instead, I am greeted with a Lua runtime error. 相反,我遇到了Lua运行时错误。 The call to create the new object seemingly works. 创建新对象的调用似乎可行。 The problem appears to be that self , in the display function, is nil. 问题似乎在于显示功能中的self为零。

self is nil because if you use the ":"-operator in lua, then lua will automatically provide the caller as first argument. self 为零是因为如果在lua中使用“:”运算符,那么lua会自动将调用者作为第一个参数提供。 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中的简单功能

luabind::object myObject = luabind::globals(L)["Person"]("John Doe");
luabind::call_member<void>(myObject, "display");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM