2. Decisions and loops
So far every line ran once, top to bottom. This page is about running some lines only sometimes, and some lines many times.
if
The lines between then and end run only when the condition is true. Change health to 80 and nothing prints.
Add else for what happens otherwise, and elseif for more cases:
Lua checks the cases from the top and takes the first one that is true. Note the spelling: elseif is one word.
Indent the lines inside with a tab. Lua does not need it, but you will.
and, or, not
Join conditions with words:
a and bis true when both are.a or bis true when at least one is.not aturns true into false and false into true.
What counts as true
In a condition, only false and nil count as false. Everything else counts as true, including the number 0 and the empty string "". That differs from many languages.
This makes "is there anything here?" a short question:
Picking a value with or and and
or gives its first value if that counts as true, and its second otherwise. That makes it a way to give a default:
a and b or c picks b when a is true and c when it is not:
You will see both in game scripts all the time.
while
while repeats for as long as its condition is true.
Something inside the loop has to change what the condition looks at. If countdown never went down, the loop would never end, and the game would freeze.
for
When you know how many times, use for. It counts for you:
i starts at 1, goes up by 1 each time round, and the loop stops after 5. A third number sets the step:
The loop's variable exists only inside the loop.
Leaving early
break leaves the loop it is in:
Loops inside loops
That is how a grid of enemies or tiles is laid out: one loop for rows, one for columns.
In a game
A game script almost never needs while. The engine already calls OnUpdate every frame, and that is the game's loop. A script decides what to do this frame and returns:
A while loop that waits for something inside OnUpdate would freeze the game, because nothing else runs until OnUpdate returns. To wait, use a timer. See Timers and coroutines.
Try it
- Print the numbers from 1 to 20, but print
Fizzin place of every number that divides by 3.n % 3 == 0is true when it does. - A chest holds 137 gold. Each trip you can carry 25. Use
whileto count the trips it takes to empty it. - Print a triangle of
#, one in the first row and five in the last.
Next: functions.