Vertilka Vertilka - 1 year ago 68
C Question

How to notify host application when object/table are garbage collected

My host C application, that embed a Lua interpreter, needs to be notified that certain object/table in running Lua script is garbage collected, so it will do something, like record this event to log file. How can I do that?

Answer Source

by adding a metatable to the userdata and adding a "__gc" function to the metatable.

Only userdata has support for the "__gc" methamethod.

One way to detect garbage collection of Lua tables is to add a canary userdata object into that table:

function create_canary(tab)
  local canary=newproxy(true)
  local meta=getmetatable(canary)
  meta.__gc = function() print("Canary is died:", tab) end
  tab[canary] = canary

C code to create and add a metatable to a userdata object:

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. */
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download