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?
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. */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With