如何在对象/表被垃圾收集时通知主机应用程序

我的主机上的 C 应用程序嵌入了 Lua 解释器,需要得到通知,即某些在运行的 Lua 脚本中的对象/表被垃圾收集时,它将执行某些操作,例如将此事件记录到日志文件中。我该如何做到这一点?

原文链接 https://stackoverflow.com/questions/4090586

点赞
stackoverflow用户98107
stackoverflow用户98107

通过为 userdata 添加元表并向元表添加 "__gc" 函数来支持垃圾回收。

Lua 5.1 中,仅 userdata 支持 "__gc" 元方法。

一种检测 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. */
}
2010-11-03 19:10:19