destructors on gc-ed lua objects
I know that Lua is gc-ed. I know that Lua can deal with 开发者_开发问答c objects via userdata.
Here is my question: is there anyway to register a function so that it's called when a C userdata object is gc-ed by lua? [Basically a destructor].
Thanks!
Yes, there is a metamethod called __gc
specifically for this purpose. See Chapter 29 - Managing Resources of Programming in Lua (PIL) for more details.
The following snippet creates a metatable and registers a __gc
metamethod callback:
luaL_newmetatable(L, "SomeClass");
lua_pushcfunction(L, some_class_gc_callback);
lua_setfield(L, -2, "__gc");
精彩评论