收集对象/表时如何通知主机应用程序
-
28-09-2019 - |
题
我的主人 C 嵌入LUA解释器的应用程序需要通知运行LUA脚本中的某些对象/表是收集垃圾的,因此它将做一些事情,例如记录此事件以记录文件。我怎样才能做到这一点?
解决方案
通过向UserData添加一个METATAT并将“ __GC”函数添加到MetaTable中。
在LUA 5.1中,只有UserData支持“ __GC” Methamethod。
检测LUA表的垃圾收集的一种方法是将Canary UserData对象添加到该表中:
function create_canary(tab)
local canary=newproxy(true)
local meta=getmetatable(canary)
meta.__gc = function() print("Canary is died:", tab) end
tab[canary] = canary
end
C代码可创建并添加一个可在用户数据对象的MetaTable:
static int userdata_gc_method(lua_State *L) {
UserObj *ud = lua_touserdata(L, 1);
/* TODO: do something */
return 0;
}
static int create_userdata_obj(lua_State *L) {
UserObj *ud = lua_newuserdata(L, sizeof(UserObj));
/* TODO: initialize your userdata object here. */
lua_newtable(L); /* create metatable. */
lua_pushliteral(L, "__gc"); /* push key '__gc' */
lua_pushcfunction(L, userdata_gc_method); /* push gc method. */
lua_rawset(L, -3); /* metatable['__gc'] = userdata_gc_method */
lua_setmetatable(L, -2); /* set the userdata's metatable. */
return 1; /* returning only the userdata object. */
}
不隶属于 StackOverflow