PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Nov 07 2019, 10:31 AM PST 5 min

A variable is essentially a name that can hold a value. Variable values can be articles/Numbers|numbers, articles/String|strings, articles/Boolean|booleans, data types, and more.

Variable Naming

In Lua, variable names can be any non-reserved string of letters, digits, and underscores, but they cannot start with a digit:

LETTERS   -- valid
a1        -- valid
var_name  -- valid
_test     -- valid
 
if        -- NOT valid
25th      -- NOT valid

Note that Lua is a case-sensitive language, meaning that TestVar and 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:

and
for
or
break
function
repeat
do
if
return
else
in
then
elseif
local
true
end
nil
until
false
not
while

Assignment

Assigning a value to a variable is done with the = operator. The output commands on lines 5–7 reveal the variable values:

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:

Variable Scope

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.

Global

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.

Local

A local variable is accessible only in the block where it’s declared. Local variables are declared using the local statement:

local x = 0  -- Local variable "x"

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 articles/Scope|Scope article.

Tags:
  • lua
  • coding
  • variable