Gc-ed lua object destructors

I know that Lua is gc-ed. I know that Lua can process c objects through user data.

Here is my question: is there a way to register a function so that it is called when the userdata C object was gc-ed from lua? [In principle, a destructor].

Thank!

+3
source share
1 answer

Yes, there is a metamethod called __gcspecifically for this purpose. See Chapter 29 - Resource Management Lua Programming (PIL) for more information.

The following snippet creates a metatable and registers a metateph callback __gc:

  luaL_newmetatable(L, "SomeClass");

  lua_pushcfunction(L, some_class_gc_callback);
  lua_setfield(L, -2, "__gc");
+7
source

Source: https://habr.com/ru/post/1743501/


All Articles