2.3 – 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 formal parameter of a function, which is a particular form of local variable):

  1. var ::= Name

Variables are assumed to be global unless explicitly declared local (see 2.4.7). Local variables are lexically scoped: Local variables can be freely accessed by functions defined inside their scope (see 2.6).

Before the first assignment to a variable, its value is nil.

Square brackets are used to index a table:

  1. var ::= prefixexp `[´ exp `]´

The first expression (prefixexp)should result in a table value; the second expression (exp) identifies a specific entry inside that table. The expression denoting the table to be indexed has a restricted syntax; see 2.5 for details.

The syntax var.NAME is just syntactic sugar for var["NAME"]:

  1. var ::= prefixexp `.´ Name

The meaning of accesses to global variables and 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.8 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.)

All global variables live as fields in ordinary Lua tables, called environment tables or simply environments. Functions written in C and exported to Lua (C functions) all share a common global environment. Each function written in Lua (a Lua function) has its own reference to an environment, so that all global variables in that function will refer to that environment table. When a function is created, it inherits the environment from the function that created it. To change or get the environment table of a Lua function, you call setfenv or getfenv (see 5.1).

An access to a global variable x is equivalent to _env.x, which in turn is equivalent to

  1. gettable_event(_env, "x")

where _env is the environment of the running function. (The _env variable is not defined in Lua. We use it here only for explanatory purposes.)