I implemented Simple Lua class in C. Usage of class:
require("test")
function foo()
local t1 = test()
local t2 = test()
t1:attach(t2)
return t1
end
o = foo()
-- some code
o = nil
attach function:
int class_attach(lua_State *L)
{
module_data_t *mod = luaL_checkudata(L, 1, "test");
luaL_checktype(L, 2, LUA_TUSERDATA);
module_data_t *child = lua_touserdata(L, 2);
printf("%p->%p\n", (void *)mod, (void *)child);
return 0;
}
After return from function t2 object is cleaned by gc.
Is it possible to prevent that. Set reference between t1 and t2 objects? (calling __gc metamethod (of t2 object) only after parent module (t1) is cleaned).
Simple way is use table:
function foo()
ret = {}
ret[1] = test()
ret[2] = test()
ret[1]:attach(ret[2])
return ret
end
but that is not fun way.
Thanks!
You can set it in the Lua registry. This is effectively a global table which can only be accessed in C code. You can set
registry[t1] = t2;. As long as you unset this appropriately int1‘s__gc. This can also scale to1:nmappings, as you could do, for example,registry[t1].insert(t2)for multiple “children”.