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 Lexical Conventions.

Any variable is assumed to be global unless explicitly declared as a local (see Local Declarations). Local variables are lexically scoped: local variables can be freely accessed by functions defined inside their scope (see Visibility Rules).

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

Square brackets are used to index a table:

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

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

var ::= prefixexp `.´ Name

All global variables live as fields in ordinary Lua tables, called environment tables or simply environments. Each function has its own reference to an environment, so that all global variables in this function will refer to this environment table. When a function is created, it inherits the environment from the function that created it. To get the environment table of a Lua function, you call getfenv. To replace it, you call setfenv.

An access to a global variable x is equivalent to _env.x, where _env is the environment of the running function. (The _env variable is not accessible in Lua. We use them here only for explanatory purposes.)