if Statements
Prerequisites: Operators
local temperature = 18
if temperature > 25 then
print("It is hot")
elseif temperature > 15 then
print("It is pleasant")
else
print("It is cold")
end
It is pleasant
if condition then ... end— every block ends withend.elseifis one word.- Parentheses around the condition are optional.
- Indentation is for readability only — Lua uses
then/endto find the block.
Combining conditions
local function describe(age, member)
if age < 0 or age > 130 then
return "invalid age"
elseif age >= 65 or member then
return "discount"
else
return "full price"
end
end
print(describe(70, false))
print(describe(30, true))
print(describe(30, false))
print(describe(-1, false))
discount
discount
full price
invalid age
Checking for nil
local config = {port = 8080}
if config.host == nil then
print("no host set")
end
if config.port then
print("port is " .. config.port)
end
no host set
port is 8080
if x then is true for any value except nil and false — including
0. Write if x ~= nil then when false is a legitimate value.
Common mistakes
- Forgetting
thenorend— Lua reports "'then' expected" or "'end' expected" with a line number. - Writing
else if(two words) — that opens a nestedif, which needs its ownend.
Practice
Given an age, print adult for 18 and over, teen for 13–17, and
child otherwise.
Show solution
local age = 15
if age >= 18 then
print("adult")
elseif age >= 13 then
print("teen")
else
print("child")
end
teen