Lua Local Variables and Scope: Blocks, Shadowing and Lifetime
Lua locals have lexical scope: a name is visible from its declaration to the end of the innermost enclosing block. Function bodies, branches, loops, and explicit do ... end regions are blocks.
Declare values close to their first use. Locals avoid accidental global state and are generally faster to access than globals.
Declaration timing
A local is not in scope inside its own initializer:
| |
This matters for recursive local functions. Use the dedicated syntax:
It is equivalent to declaring the local first and assigning the function afterward.
Multiple assignment
Lua evaluates right-hand expressions before assignment, which makes swaps safe. Missing values become nil, and extra values are discarded, subject to Lua’s multiple-return adjustment rules.
Shadowing and lifetime
An inner declaration may shadow an outer name:
Use shadowing sparingly because identical names can make reviews confusing. A local normally becomes collectible after its block and all closures capturing it are gone. Scope is therefore both a naming rule and part of object lifetime.