Weak table and GC finalizer using C API

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 06:53:15

As the Lua manual states:

Only objects that have an explicit construction are removed from weak tables. Values, such as numbers and light C functions, are not subject to garbage collection, and therefore are not removed from weak tables (unless its associated value is collected).

Your my_func is pushed without any upvalues, so it is a light C function, and it isn't removed from weak tables during garbage collection, so the associated userdata does not become garbage before you close the Lua state. Your code should work if you use a Lua function instead of my_func, or if you push my_func with upvalues (and if you fix the order of the arguments in the lua_gc call!).

To summarize, the following value types are not removed from weak tables (given that their associated keys/values aren't removed either):

  • booleans
  • numbers
  • strings
  • light userdata
  • light C functions (Lua 5.2 only)

As a consequence your program should work fine with Lua 5.1 because there are no light C functions (you still have to fix the lua_gc call).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!