Lua If Statements
An if statement runs a block only when a condition is true. Lua's form is if … then … end, with optional elseif and else branches.
local battery = 15
if battery < 20 then
print("Low battery, plug in soon")
end
if battery > 50 then
print("Plenty left")
else
print("Less than half")
endLow battery, plug in soon
Less than half
elseif chains
Write elseif as one word. The branches are tested from top to bottom, and only the first matching one runs:
local function grade(score)
if score >= 90 then
return "A"
elseif score >= 80 then
return "B"
elseif score >= 70 then
return "C"
else
return "F"
end
end
for _, s in ipairs({ 95, 83, 70, 42 }) do
print(s, grade(s))
end95 A
83 B
70 C
42 F
Note:
else if(two words) is legal but starts a nestedifthat needs its ownend. Forgetting it gives the error "'end' expected".
Conditions and truthiness
Any value can be a condition. Only nil and false count as false, so 0 and "" are true. This makes checking for "missing" values short:
local user = { name = "Mia", email = nil }
if user.email then
print("Send mail to " .. user.email)
else
print(user.name .. " has no email")
end
local count = 0
if count then print("0 is true in Lua!") end
if count == 0 then print("compare explicitly for zero") endMia has no email
0 is true in Lua!
compare explicitly for zero
Combining conditions
Use and, or and not. Parentheses make intent clear:
local age, hasTicket, isVip = 17, true, false
if age >= 18 and hasTicket then
print("Welcome")
elseif isVip or (hasTicket and age >= 16) then
print("Welcome with a guardian")
else
print("Sorry")
end
if not isVip then print("Regular entrance") endWelcome with a guardian
Regular entrance
The "ternary" idiom
Lua has no ?: operator. For simple cases, cond and x or y works as long as x is never nil or false:
local temperature = 28
local advice = temperature > 25 and "shorts" or "jeans"
print(advice)
-- the pitfall: x is false
local flag = true and false or "fallback"
print(flag)shorts
fallback
No switch statement
Lua has no switch. Use an elseif chain, or, when you map values to results, a table lookup, which is often clearer and faster:
local handlers = {
start = function() return "Starting engine" end,
stop = function() return "Stopping engine" end,
}
local function command(name)
local handler = handlers[name]
if handler then
return handler()
end
return "Unknown command: " .. name
end
print(command("start"))
print(command("fly"))Starting engine
Unknown command: fly
Common mistakes
| Mistake | Fix |
|---|---|
if x = 5 then |
use == for comparison |
if x != 5 then |
Lua writes ~= |
if x > 5 (no then) |
add then |
else if without a second end |
write elseif |
if count then to test for zero |
if count == 0 then |
Test yourself
How is "else if" written as one branch of an if chain?
else ifelifelseifelsif
Does if 0 then print("yes") end print yes?
- Yes
- No
- It is a syntax error
- Only in Lua 5.1
What is the usual Lua replacement for a switch on string values?
- A
gototable - A table that maps each value to a result or function
string.switch- There is none