adding a metatable to user data and adding the __gc function to the metatable.
In Lua 5.1, only user data supports the __gc metamethod.
One way to detect garbage collection in Lua tables is to add the canary userdata object to this 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 meta tag to the userdata object:
static int userdata_gc_method(lua_State *L) { UserObj *ud = lua_touserdata(L, 1); return 0; } static int create_userdata_obj(lua_State *L) { UserObj *ud = lua_newuserdata(L, sizeof(UserObj)); lua_newtable(L); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, userdata_gc_method); lua_rawset(L, -3); lua_setmetatable(L, -2); return 1; }
Neopallium
source share