[英]Store Lua class object to C pointer and push it back to Lua Stack
Using a home made Lua C++ binding I'm able to create C++ classes that are available from Lua scripts. 使用自制的Lua C ++绑定,我可以创建可从Lua脚本获得的C ++类。
Now I would like to create class objects in a Lua script, store its reference in C++ and when required call a function of this Lua class object from the C++ code. 现在,我想在Lua脚本中创建类对象,将其引用存储在C ++中,并在需要时从C ++代码中调用此Lua类对象的函数。
In a Lua script I created a class object with a global function to pass it to the C++ code. 在Lua脚本中,我创建了一个带有全局函数的类对象,将该类对象传递给C ++代码。
MyClass = {}
function MyClass:hello()
debug.codeSite.sendMsg( "MyClass:hello()" )
end
function MyClass:new()
local tNewClass = {}
setmetatable( tNewClass, self )
self.__index = self
return tNewClass
end
local tClass = MyClass:new()
function getClass()
debug.codeSite.sendMsg( "Return class object" )
return tClass;
end
Now in C++ I would like to get its instance and call the function hello(). 现在在C ++中,我想获取其实例并调用函数hello()。 Here what I tried :
这是我尝试的:
At this point I don't know how to push back this pointer to the Lua stack, so the Lua table is pushed back to the stack, push the function name and then call it. 在这一点上,我不知道如何将这个指针推回Lua堆栈,因此Lua表被推回了堆栈,压入了函数名,然后调用了它。
The idea of all of this is to create several objects in Lua scripts and use them in C++. 所有这些的想法是在Lua脚本中创建几个对象,然后在C ++中使用它们。
In lua: 在lua中:
tObject1 = MyClass:new()
tObject2 = MyClass:new()
and in C++ use tObject1:hello() or tObject2:hello() when required. 在C ++中,在需要时使用tObject1:hello()或tObject2:hello()。
Edit: 编辑:
According to this description of lua_topointer() , converting Lua table to C pointer is only for debugging purpose. 根据lua_topointer()的描述 ,将Lua表转换为C指针仅用于调试目的。
Thanks. 谢谢。
Store lua objects in predefined Lua registry table with luaL_ref(), and save returned integer index in c++. 使用luaL_ref()将lua对象存储在预定义的Lua注册表中,并在c ++中保存返回的整数索引。 When you need Lua object put on Lua stack, read it from registry with lua_rawgeti(), using index retrieved earlier.
当您需要将Lua对象放在Lua堆栈上时,请使用较早检索到的索引通过lua_rawgeti()从注册表中读取它。 Don't forget to unref object with luaL_unref() when you don't need it on c++ side anymore.
当您不再需要c ++方面的对象时,请不要忘记使用luaL_unref()取消引用对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.