Variables
Variables are used to store data that can be referenced throughout the code.
Lua has two main types of variables: global variables, which can be used anywhere in a program, and local variables, which can only be referenced in the block where they’re defined.
Creating and Accessing Variables
A variable name can include letters, numbers, and underscores, but must begin with a letter or an underscore. A variable name cannot include a space or any other character. Variables do not need to be declared with a value, if a variable is called and it hasn’t been assigned a value it will return nil
.
a = 10
After defining a variable, it can be referred to at any point in the code.
a = 10print(a)
Lua also supports multiple assignment, such as in the example below.
b, c = "spam", "eggs"print(c) -- This will print eggs
Scope
In Lua, a variable is assumed to be global unless it is explicitly declared as a local variable using the local
keyword.
count = 2function addValue (val)local count = 1return count + valendprint(addValue(5)) -- Returns 6print(count) -- Returns 2
Note: In the code above, if the
local count = 1
statement is omitted theaddValue()
function will use the global value instead and return 7.
Reassigning Variables
To modify the value of a variable, assign a new value.
a = 10print(a) -- This will print 10a = 5print(a) -- This will print 5
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.