if, elseif and else Statements
Write conditional branching logic with Lua's if/elseif/else syntax.
Basic if Statement
The if statement evaluates a condition and executes its block when the condition is truthy. In Lua, only false and nil are falsy; everything else — including 0 and "" — is truthy. End the block with end.
local score = 85
if score >= 90 then
print("A grade")
end
if score >= 60 then
print("Passing") -- prints
end
if 0 then
print("0 is truthy!") -- prints in Lua
endif/elseif/else
Chain multiple conditions with elseif and provide a fallback with else. Lua evaluates conditions top to bottom and executes only the first matching branch. Unlike switch/case in other languages, Lua's elseif is a single keyword (not else if).
local score = 75
if score >= 90 then
print("A")
elseif score >= 80 then
print("B")
elseif score >= 70 then
print("C") -- prints
elseif score >= 60 then
print("D")
else
print("F")
endAll lessons in this course
- if, elseif and else Statements
- while and repeat-until Loops
- Numeric for Loop
- Generic for and break