Lua: Control Flow
What you will learn
Lua uses if/elseif/else (note: elseif is one word!), numeric and generic for loops, and while.
Conditionals
local score = 85
if score >= 90 then
print("A")
elseif score >= 80 then
print("B")
else
print("F")
end
Lua spells elseif as one word (unlike most languages that use else if). Blocks close with end.
Numeric for loop
for i = 1, 5 do
print(i) -- 1, 2, 3, 4, 5
end
for i = 1, 10, 2 do
print(i) -- 1, 3, 5, 7, 9 (step = 2)
end
Syntax: for var = start, stop, step do (step defaults to 1). The loop includes both start and stop.
Generic for loop (iterating over tables)
local fruits = {"apple", "banana", "cherry"}
-- Iterate over array indices
for i, v in ipairs(fruits) do
print(i, v) -- 1 apple, 2 banana, 3 cherry
end
-- Iterate over all key-value pairs (including non-sequential)
for k, v in pairs(fruits) do
print(k, v)
end
ipairs() iterates over sequential integer keys. pairs() iterates over all key-value pairs.
While loop
local i = 0
while i < 5 do
print(i)
i = i + 1
end
Common mistakes
- Writing
else if(two words) instead ofelseif(one word) — compile error. - Forgetting
doafterforandwhile—for i = 1, 5 donotfor i = 1, 5. - Using
ipairs()on a dictionary table (it only returns sequential integer keys). - Forgetting
endto close blocks.
Quick check below!