Lua Userdata __gc Metamethod and Finalization Order
0 reputation · 04 May 2021, 14:47 UTC
Lua 5.4 utilizes a garbage collector that handles userdata reclamation via the __gc metamethod. When multiple unreachable objects are identified during a collection cycle, the language specification does not define a strict order for the execution of their respective finalizers.
This lack of deterministic ordering creates a challenge when managing interdependent resources. If one finalizer depends on a resource managed by another unreachable object, the sequence of execution may lead to inconsistent states or delayed reclamation of underlying system handles.
Given these constraints, what is the recommended pattern for ensuring safe cleanup of interdependent userdata? Is there a mechanism to define a priority or dependency chain for __gc execution?