Codectionary / Developer documentation / Lua

Lua 5.4 deterministic cleanup

Lua 5.4 <close> locals call a value's __close metamethod at scope exit, including error unwinding. This supports deterministic cleanup; the syntax is not supported in Luau.

Syntax

local resource <close> = closableValue

Examples

Lua 5.4 deterministic cleanup

Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.

local function acquire()
    return setmetatable({}, {
        __close = function(_, err)
            print(err == nil and "closed normally" or "closed after error")
        end
    })
end
do
    local resource <close> = acquire()
    print("working")
end
  1. Output: working, then closed normally. The resource closes at the end of the do block.

Best practices

  • Keep cleanup reliable and avoid raising new errors while handling a failure. A to-be-closed binding is also non-reassignable.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading