我的宿主c应用程序嵌入了lua解释器,需要通知运行lua脚本的某些对象/表被垃圾收集,所以它将执行一些操作,比如将此事件记录到日志文件中。我该怎么做?
最佳答案
通过向userdata添加一个元表并向元表添加一个“\ugc”函数。
In Lua 5.1, only userdata has support for the "__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
创建元表并将其添加到userdata对象的C代码:
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. */
}