简体   繁体   中英

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM