本文介绍了在luabind :: object中存储带父类的lua类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C ++ lua 5.1 luabind 0.7-0.81

创建一个带父类的lua类,并将其存储在luabind :: object中。

Trying to create a lua class with parent and store it in a luabind::object.

Lua

class 'TestClassParent'
function TestClassParent:__init()
    print('parent init\n')
end
function TestClassParent:__finalize()
    print('parent finalize\n')
end

class 'TestClass' (TestClassParent)
function TestClass:__init()
    print('init\n')
    TestClassParent.__init(self)
end
function TestClass:__finalize()
    print('finalize\n')
end

C ++

{
    luabind::object obj = luabind::call_function<luabind::object>(lua_state, "TestClass");
}
printf("before GC\n");
lua_gc(lua, LUA_GCCOLLECT, 0);
printf("after GC\n");

输出

初始化

父级初始化

在GC之前

在GC之后

Output:
init
parent init
before GC
after GC

结果: destroy,'TestClass'实例在垃圾收集循环后仍然存在(__finalize方法未被调用,内存不被释放)。

Moresome 如果我使用没有父类的类,垃圾被正确收集。

Result: After obj is destroyed, 'TestClass' instance is still alive after garbage collection cycle (__finalize method is not called and memory is not freed). It's destroying only on program exit.
Moresome if I use class without parent, garbage is collected correctly.

如果我尝试使用采用政策(获取已创建对象的所有权)

If I try to use adopt policy (to take ownership of created object)

luabind::object obj = luabind::call_function<luabind::object>(lua_state, "TestClass")[luabind::adopt(luabind::result)];

我得到:


  • luabind 0.7 中显示的结果与未采用政策时相同

  • 要使用unregistrerd类型

  • in luabind 0.7 - same result as without adopt policy
  • in luabind 0.81 - crash with message "you are trying to use an unregistrerd type"

如何正确在C ++中创建lua对象

推荐答案

这是一个在0.8.1中的已知错误;对最后构造的对象的引用留在超级函数上值中。它已在0.9-rc1中修复:

This is a known bug in 0.8.1; a reference to the last constructed object is left in the "super" function upvalue. It has been fixed in 0.9-rc1:

这篇关于在luabind :: object中存储带父类的lua类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 05:50