Lua Assignment
Assignment is storing a value in a variable with the = sign. One line can store values in several variables at once.
A counter grows step by step
Each update reads the current value, adds to it and stores the result back. The prints show the value after every step.
local counter = 0
print(counter)
counter = counter + 1
print(counter)
counter = counter + 5
print(counter)One line assigns two variables
The names on the left match the values on the right in order. The print call shows both values separated by a tab.
local a, b = 1, 2
print(a, b)A swap needs no spare variable
The values on the right are worked out before anything is stored. That is why the old values can trade places safely.
local x = 10
local y = 20
print(x, y)
x, y = y, x
print(x, y)Example
local scoreA = 7
local scoreB = 12
scoreA, scoreB = scoreB, scoreA
print(scoreA, scoreB)
local total = 0
total = total + scoreA
total = total + scoreB
print(total)Key points
- Store: local name = value saves the value under that name.
- Update: assigning to the same name again replaces the old value.
- Multiple assignment: local a, b = 1, 2 stores one value in each variable, in order.
- Swap: a, b = b, a swaps two values without a spare variable.
- Right side first: Lua works out all the values on the right before it stores any of them.
In this example, the two scores trade places in one line, so scoreA holds 12 and scoreB holds 7. The total starts at 0 and each score is added to it in turn. The final print shows the total of 19.
Note
Lua has no += sign, so an update spells out the full line counter = counter + 1.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line adds 1 to a variable named count in Lua?