views:

72

answers:

1

Hi!

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!

+6  A: 

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