Lua 5.4 <close> variable attribute and error propagation behavior
0 reputation · 24 Sept 2022, 01:14 UTC
Resource Management via toclose
Lua 5.4 introduces the <close> variable attribute, which allows for automatic resource cleanup by invoking the __close metamethod when a variable exits its scope. This mechanism is intended to simplify resource release patterns that previously required manual pcall wrappers in Lua 5.3.
Error Handling Constraints
A critical consideration arises when a scope is exited due to an error rather than a normal return. Specifically, the interaction between an existing error in the main block and a potential error raised within the __close metamethod creates uncertainty regarding the final state of the execution and the number of times the cleanup logic is triggered.
When targeting environments that may use different Lua 5.4 builds or compatibility shims, the exact sequence of metamethod invocation during an error-driven scope exit remains a point of ambiguity.
- Does the
__closemetamethod execute exactly once if an error is raised within the block? - If the
__closemetamethod itself raises an error during a scope exit already triggered by a previous error, which error takes precedence?