我的主人 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. */
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top