Comment notifier l'application hôte lorsque l'objet / la table sont garbage collection
-
28-09-2019 - |
Question
Mon hôte C l'application, qui comportent un interprète Lua, doit être informé que certains objets / table en cours d'exécution de script Lua est nettoyé, il fera quelque chose, comme enregistrer cet événement dans le journal fichier. Comment puis-je faire?
La solution
en ajoutant un métatable au userdata et en ajoutant une fonction « __gc » du métatable.
Dans Lua 5.1, seulement UserData a le soutien de la "gc" methamethod.
Une façon de détecter la collecte des ordures de tables Lua est d'ajouter un objet userdata canari dans ce tableau:
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
le code C pour créer et ajouter un métatable à un objet userdata:
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. */
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow