Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 312
anon Avatar asked Jun 13 '26 19:06

anon


1 Answers

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");
like image 174
Judge Maygarden Avatar answered Jun 17 '26 05:06

Judge Maygarden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!