Nanfeng

Notes on software development, code, and curious ideas

Control Structures in Lua

Lua provides familiar conditional and loop constructs with a few important semantic details. Only false and nil are false; zero and the empty string are true.

Conditions

1
2
3
4
5
6
7
if score >= 90 then
grade = "A"
elseif score >= 80 then
grade = "B"
else
grade = "C"
end

and and or return operands rather than forced booleans. The common value or fallback idiom therefore replaces false as well as nil.

Loops

1
2
3
4
5
6
7
8
9
local i = 1
while i <= 3 do
print(i)
i = i + 1
end

repeat
i = i - 1
until i == 0

A repeat body runs at least once, and variables declared in the body remain visible in its until condition.

Numeric for evaluates its bounds and step once:

1
2
3
for value = 10, 1, -1 do
print(value)
end

The loop variable is local to the loop and should not be reassigned. Generic for uses an iterator:

1
2
3
for key, value in pairs(settings) do
print(key, value)
end

break exits the innermost loop. return exits a function and must be the last statement in its block unless wrapped in a nested do ... end. Lua also supports restricted goto labels, which can simplify cleanup or continue-like flow but cannot jump into the scope of a local variable.

Prefer straightforward branches and small functions. A control structure is clearest when loop termination, mutation, and exceptional exits are visible without tracing distant state.

+