Saving lua class with parent in luabind :: object

Using C ++ , lua 5.1 , luabind 0.7-0.81

Trying to create a lua class with a 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");

Exit :
INIT
parent init
before GC
after GC

Result: After destroying obj, the TestClass instance is still alive after the garbage collection cycle (the __finalize method is not called and the memory is not freed). This only destroys the output of the program.
Moresome , if I use a class without a parent, the garbage collects correctly.

If I try to use accept policy (to get ownership of the created object)

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

:

  • luabind 0.7 - , .
  • luabind 0.81 - " unregistrerd"

lua ++ ?

+3
3

: OP, , .

,

. , :

// initialization
lua_State* lua = lua_open();
luaL_openlibs(lua);
luabind::open(lua);
// declare class
luaL_loadstring(lua, 
    "class 'TestClass'\
     function TestClass:__init() print('init') end\
     function TestClass:__finalize() print('finalize') end");
lua_pcall(lua, 0, LUA_MULTRET, 0);
// instantiate
{
    luabind::object obj = luabind::call_function<luabind::object>(lua, "TestClass");
}
// collect
printf("Before GC collect\n");
lua_gc(lua, LUA_GCCOLLECT, 0);
printf("After GC collect\n");
lua_close(lua);

:

init
Before GC collect
finalize
After GC collect

lua 5.1.4, luabind 0.81 VC8 (aka VS2005) SP1

+1

luabind::. . . . - Luabind ( )

0

Source: https://habr.com/ru/post/1726236/


All Articles