Lua Scoping |
|
Some pages concerning Lua variable scoping:
VersionNotice: The following is only true for versions of lua prior to 4.1work3. Current Lua versions have full lexical scoping.
This page will describe Lua's scoping rules. Furthermore it will attempt to do so without using the terms "static scoping" and "lexical scoping" whose meaning can vary depending on the person or text (see LuaScopingDiscussion).
local
qualifier.
The binding of variable names is, to use a taboo word, static. This is a useful property because it means you can always determine what variable a given name is bound to from the source code. In contrast, in a language with dynamic binding, this may depend on context.
Scopes are created naturally by functions, control constructs (for
, if
, etc.), and chunks. A scope can also be created explicitly using do...end
.
%
produces a copy of that variable as of the function's instantiation. Only the immediate scope containing the function and the global scope may be accessed in this manner.
Since the variable is a copy, it's not possible for the function to alter the original value. A common solution to this problem is to put such variables inside a table and access the table as an upvalue. The table acts as a function closure.
local closure = { a=5 } local foo = function() %closure.a = %closure.a + 1 %closure.b = 'hello' end
Someone may tell you that upvalues are a feature of Lua, but don't believe it.
globals
. The local scope can also be accessed using debugging interfaces.