开发者

destructors on gc-ed lua objects

开发者 https://www.devze.com 2022-12-28 13:26 出处:网络
I know that Lua is gc-ed. I know that Lua can deal with 开发者_开发问答c objects via userdata.

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

精彩评论

暂无评论...
验证码 换一张
取 消