Lua Control Statements
Learn conditional branches and loops, the essential control statements used to build Lua programs.
Conditional Branches with if and else
Use if, elseif, and else to select a branch.
if condition then
statements
elseif another_condition then
statements
else
statements
end
score = 70
if score >= 60 then
print("Pass")
else
print("Fail")
end
Use == for equality and ~= for inequality.
In Lua, only false and nil are false conditions. Unlike C, the number 0 is true.
Relational Operators
| Operator | Meaning |
|---|---|
x < y |
x is less than y |
x > y |
x is greater than y |
x <= y |
x is less than or equal to y |
x >= y |
x is greater than or equal to y |
x == y |
x equals y |
x ~= y |
x does not equal y |
Loops
Use while to repeat while a condition is true.
i = 1
while i <= 10 do
print(i .. ": Hello world!")
i = i + 1
end
Use numeric for when the range is known.
for i = 1, 10 do
print(i .. ": Hello world!")
end
Specify a step as the third value.
for i = 1, 10, 4 do
print(i)
end
Use repeat when the loop body must run at least once. The loop ends when the until condition becomes true.
i = 1
repeat
print(i)
i = i + 1
until i >= 5
Use break to exit a loop early.
for i = 0, 10 do
print(i)
if i == 5 then break end
end
Lua does not provide built-in switch or continue statements.
Example: Multiplication Table
for i = 1, 9 do
for j = 1, 9 do
io.write(string.format("%3d", i * j))
end
io.write("\n")
end
io.write() does not add an automatic newline. The %3d format reserves three character positions.