How to notify the host application when an object / table is garbage collected

In my C host application with the Lua interpreter built in, it should be reported that a specific object / table at the start of the Lua script is garbage collection, so it will do something like write this event to register a file. How can i do this?

+7
c garbage-collection object lua-table lua
source share
1 answer

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); /* 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 metatable. */ return 1; /* returning only the userdata object. */ } 
+12
source share

All Articles