Control Flow
The usual shapes are all here: conditionals, two kinds of loop, and a numeric
for.
None of it needs parentheses around the condition.
if / elseif / else
local score = 72
if score >= 90 then
print("A")
elseif score >= 70 then
print("B")
else
print("C or lower")
end
Comparisons are == and ~= (not !=). Logical
operators are spelled out: and, or, not. Both
and and or short-circuit, which makes x = x or default
a common idiom for filling in a default value.
while and repeat
repeat ... until checks its condition after the body runs, so the body
always executes at least once, and unlike while, locals declared inside
the body are still visible in the until condition.
local n = 5
while n > 0 do
print(n)
n = n - 1
end
repeat
local line = read_next()
until line == nil
Numeric for
for var = start, stop[, step] do. The step defaults to 1 and can be
negative to count down. The loop variable is local to the loop; it does not leak.
for i = 1, 5 do
print(i)
end
for i = 10, 0, -2 do
print(i) -- 10, 8, 6, 4, 2, 0
end
Generic for
For iterating a table, reach for pairs (every key) or
ipairs (the 1..n array part, in order, stopping at the first hole). More
on why the distinction matters in Tables.
local colors = { "red", "green", "blue" }
for index, value in ipairs(colors) do
print(index, value)
end
break, and no continue
break exits the innermost loop. Lua has no continue
keyword; the common workaround is wrapping the rest of the loop body in an
if, or using goto with a label at the end of the loop body.