Rules for disabling Lua state and garbage collection methods

tl; dr version: is metamont garbage collection safe during Lua state shutdown if it accesses global variables? What about local values?


When a lua_State closed using lua_close , the Lua documentation states that all objects are deleted . And it says that any related garbage metadata is collected.

Great.

However, there are two possible uses for GC metamethods that are uncertain in this paradigm:

  • What if you have a GC metamethod that uses a local variable that stores a collection value. Say a string, a function, etc. That is, your GC metamethod is defined as follows:

     local some_string = "string" function mt:__gc() --[[Do something with some_string]] end 

    What happens in this case? Is it possible to collect some_string ? I know that if the object in which the metatable is located is collected under normal conditions, this is not possible. Lua guarantees that the value of some_string will remain until the GC function itself is built.

    But since all objects are destroyed on lua_close , is it possible that the values โ€‹โ€‹of the GC function can be destroyed before the function will be? I do not think this is (since it can cause all kinds of problems), but I am looking for a real answer, and not what I think.

  • I admit that problem # 1 is unlikely to be a problem, as this will create a lot of problems with the GC metamethods. However, this is a completely different matter:

     local some_string = "string" function mt:__gc() print(some_string) end 

    It looks like # 1, but it is not. What for? Because it accesses a global variable. Namely, print .

    There is no direct connection between the function and any value stored in print (as opposed to case 1, where some_string explicitly the value of the function). Thus, it is possible to assemble print before calling the function when the Lua state is turned off.

The question is: is it safe to use the garbage collection metamet ever to use something from the global table (ignoring the possibility of deliberate sabotage of the vis-a-vis print = nil global table) while turning off the Lua state? Or, as a rule, should they always explicitly do any functions or data that they relate locally? Will this be enough to avoid problems?

+4
source share
1 answer

Any data accessible from the __gc method is safe to access; this includes both local and accessible tables, such as _G , which contains print .

What could be the problem with (un-) loaded C libraries; this affects Lua 5.1 and is fixed in Lua 5.2.1. See Patch for "Finalizers can call functions from a dynamic library after the library has been unloaded . "

+3
source

All Articles