A closure is a function together with the external local variables it captures. The captured variables remain alive after their original block returns.
1 | local function newCounter(start) |
Each call to newCounter creates a separate value. Multiple closures created in the same call can deliberately share one variable:
1 | local function newBox(value) |
Higher-order functions
Functions are ordinary values in Lua, so they can be arguments and results:
1 | local function greaterThan(limit) |
This is useful for event callbacks, iterators, configuration, memoization, and private object state.
Loop capture
When callbacks are created in a loop, capture a per-iteration local if the code must work consistently across Lua versions and transformations:
1 | local callbacks = {} |
Closures can extend the lifetime of large tables or resources accidentally. If a long-lived callback needs only one field, capture that value instead of the entire object, and unregister callbacks when their owner is destroyed.