Lua If Else
An else branch gives an if statement a second block, which runs when the condition is false. Exactly one of the two blocks runs each time the statement is reached.
An odd number takes the else branch
The remainder check asks whether 7 divides evenly by 2, and it does not. So the else block prints the label Odd.
local number = 7
if number % 2 == 0 then
print("Even")
else
print("Odd")
endA cold temperature takes the else branch
The temperature of 12 is below 20, so the condition is false. The else block prints the Cold label.
local temp = 12
if temp >= 20 then
print("Warm")
else
print("Cold")
endA low battery takes the else branch
The battery level of 15 is below the safe level of 20. Only the else label prints, which proves that one branch ran.
local battery = 15
if battery >= 20 then
print("Battery ok")
else
print("Battery low")
endExample
local score = 68
local passMark = 50
if score >= passMark then
print("Result: Pass")
else
print("Result: Fail")
end
print("Score: " .. score)Key points
- Else meaning: the else block runs when the if condition gives false.
- No own condition: else needs no condition written after it.
- One branch only: either the if block or the else block runs, and never both.
- Shape: else sits between the if block and the closing end.
- Even check: number % 2 == 0 gives true when a number divides evenly by 2.
- Two outcomes: if and else together suit a choice between exactly two results.
In this example, the score of 68 reaches the pass mark of 50, so the if block prints the Pass result. The else block is skipped, because exactly one branch runs. The last line then prints the score itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
When does the else block run?