Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 524
Vertilka Avatar asked Nov 03 '10 18:11

Vertilka


Video Answer


1 Answers

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

In Lua 5.1, 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
end

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. */
}
like image 123
Neopallium Avatar answered Oct 01 '22 22:10

Neopallium