CでSimple Luaクラスを実装しました。クラスの使用法:
require("test")
function foo()
local t1 = test()
local t2 = test()
t1:attach(t2)
return t1
end
o = foo()
-- some code
o = nil
アタッチ機能:
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;
}
関数 t2 から戻った後、オブジェクトは gc によって消去されます。それを防ぐことは可能ですか?t1 オブジェクトと t2 オブジェクト間の参照を設定しますか? (親モジュール (t1) が消去された後にのみ、(t2 オブジェクトの) __gc メタメソッドを呼び出します)。
簡単な方法はテーブルを使用することです:
function foo()
ret = {}
ret[1] = test()
ret[2] = test()
ret[1]:attach(ret[2])
return ret
end
しかし、それは楽しい方法ではありません。ありがとう!