3.2 – Variables
Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table fields.
A single name can denote a global variable or a local variable (or a function's formal parameter, which is a particular kind of local variable):
var ::= Name
Name denotes identifiers, as defined in §3.1.
Any variable name is assumed to be global unless explicitly declared as a local (see §3.3.7). Local variables are lexically scoped: local variables can be freely accessed by functions defined inside their scope (see §3.5).
Before the first assignment to a variable, its value is nil.
Square brackets are used to index a table:
var ::= prefixexp ‘[’ exp ‘]’
The meaning of accesses to table fields can be changed via metatables. An access to an indexed variable t[i]
is equivalent to a call gettable_event(t,i)
. (See §2.4 for a complete description of the gettable_event
function. This function is not defined or callable in Lua. We use it here only for explanatory purposes.)
The syntax var.Name
is just syntactic sugar for var["Name"]
:
var ::= prefixexp ‘.’ Name
An access to a global variable x
is equivalent to _ENV.x
. Due to the way that chunks are compiled, _ENV
is never a global name (see §2.2).