This article is part of a larger series on the Lua Basics.
- Please check out the Lua Basics if you haven't already.
- For more documents within this series, please scroll to the bottom of the page or click here.
Variables are the way Lua stores values for later use. Think of them like several labeled boxes. For our purposes, each box contains one value. Whenever you ask for the contents of a specific variable, Lua looks for it, finds it, and reports back with the contents.
Declaring a Variable
Variables can be made by typing a variable name, an equal sign (=
), and a value or expression. They can then be used in place of values and can be modified later within a script.
a = "Hello, World!" -- Here, we store the string value "Hello, World!" within the variable "a"
print(a) --> Hello, World!
a = a .. " You are amazing!" -- We add " You are amazing!" to the end of "Hello, World!" to form...
print(a) --> Hello, World! You are amazing!
Lua is a dynamically typed language, which means that any variable can hold any value regardless of what it originally held.
a = "Hello, World!"
a = 5
a = true
print(a) --> true
Valid Names
Variable names...
- Can only use alphanumeric characters and underscores (
_
). - Must not start with a number.
- Cannot be the same as a Lua keyword (
and
,or
,if
,while
, etc.)
For instance...
- ✅
a
is a valid variable name. - ✅
_b
is a valid variable name. - ✅
aBc123
is a valid variable name. - ❌
123abc
is an invalid variable name; variable names cannot start with a number. - ❌
foo-bar
is an invalid variable name; variable name can only use alphanumeric characters and underscores (_
) - ❌
and
is an invalid variable name; variable names cannot be the same as a Lua keyword. - ❌
local
is an invalid variable name; variable names cannot be the same as a Lua keyword.
Issues with Global Variables
By default, new variables declared within Lua are global. This means that they can be used anywhere within the Lua environment once declared. This can lead to some adverse effects.
For starters, scripts can cause interference with other scripts if they all use the same name for a global variable.
These issues can be fixed with local variables.
Local Variables
Local variables are limited to their own scope, meaning that only instructions within it can access their contents. A new local variable can be created by putting local
behind the first declaration of the variable.
To use the same local variable within the same scope, make sure to not use the local
tag for the variable again. If not...
local var = 5
do
print(var) --> 5
local var = var*2
print(var) --> 10
end
print(var) --> 5