Variables and assignment
A variable is a name that holds a value, and you can change what it holds at any time.
In this page:
Variables and assignment
Assign with a single equals sign. Variables have no declared type, only values do, so the same variable can hold a number and later a string. Lua supports multiple assignment, so a, b = b, a swaps two values without a temporary.
Note:
Names are case sensitive and may contain letters, digits and underscores but cannot start with a digit.
Example: Variables and assignment
local x = 10
x = "now a string"
print(x)
local a, b = 1, 2
a, b = b, a
print(a, b)
local p, q, r = 1, 2
print(p, q, r)
-- Output:
-- now a string
-- 2 1
-- 1 2 nil
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using a reserved word like end or function as a name
- Expecting a declared type to be enforced
- Assuming a, b = 1 gives b the value 1
Chapter Summary
- Assign with =
- Variables hold any type
- Multiple assignment swaps values
- Missing values become nil
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: