Lua by Example: Conditionals
Conditional logic uses `if`, `elseif`, and `else`. This example shows how to control program flow based on boolean checks.
Code
local score = 85
if score >= 90 then
print("Grade: A")
elseif score >= 80 then
print("Grade: B")
elseif score >= 70 then
print("Grade: C")
else
print("Grade: F")
end
-- Ternary operator idiom
-- (condition and true_val or false_val)
local status = (score >= 50) and "Pass" or "Fail"
print("Status: " .. status)
-- False and nil are false, everything else is true
if 0 then
print("0 is true in Lua!")
endExplanation
The if statement in Lua is straightforward, using the keywords if, then, elseif, else, and end. It is important to note that elseif is one word; writing else if is a syntax error. Blocks are always terminated with end, eliminating the need for curly braces or indentation sensitivity.
Lua does not have a built-in ternary operator (like ? : in C). However, the idiom a and b or c is commonly used to achieve the same result. Because and returns its second argument if the first is true, and or returns its first argument if it is true, this expression evaluates to b if a is true, and c otherwise (assuming b is not false/nil).
A common pitfall for beginners is Lua's truthiness rules. Only false and nil are treated as false. Everything else evaluates to true. This includes the number 0 and the empty string "", which are considered true in Lua, unlike in C or JavaScript.
Code Breakdown
elseif allows chaining conditions. Note the spelling (no space).and "Pass" or "Fail" relies on short-circuit evaluation to simulate a ternary operator.
