A variable is essentially a name that can hold a value. Variable values can be
articles/Boolean|booleans, data types, and more.
In Lua, variable names can be any non-reserved string of letters, digits, and underscores, but they cannot start with a digit:
Note that Lua is a case-sensitive language, meaning that
TESTVAR are two unique names. As a convention, names which begin with an underscore followed by uppercase letters (such as
_VERSION) should be avoided, as they may be reserved for internal global Lua variables.
Reserved Names in Lua
The following keywords are reserved by Lua and cannot be used as variable or function names:
Assigning a value to a variable is done with the
= operator. The output commands on lines 5–7 reveal the variable values:
=while the value is on the right side.
Once declared, a variable’s value can be changed by simply assigning another value to it:
Lua even lets you set or change multiple variables in the same command by separating each variable-value pair with a comma:
In Lua, variables exist in one of two possible scopes, global or local. All variables will default to global unless they are declared as local.
A global variable is visible to all scopes of a script. In the following code, the global variable
x starts at 0, increments by 1 in each iteration of the
for loop, and is printed again afterward with a final value of 5.
A local variable is accessible only in the block where it’s declared. Local variables are declared using the
In the following example, the initial local variable
x is set to 0, and another local variable
x is declared inside the
for loop. As the loop iterates, its locally-scoped
x is printed with a constant value of 1, then the initial variable
x is printed with an unchanged value of 0.
For more information on scope and how it applies to Lua scripting, see the