Conditionals in Lua
Lua provides branching control flow through the if, elseif, and else keywords. Every if statement must be closed with an explicit end, and each branch's condition is introduced with then rather than curly braces. Lua has no built-in switch statement, so chained elseif blocks (or, for many discrete cases, a table lookup) are the idiomatic way to express multi-way branching.
Cricket analogy: On-field captain choosing to bowl or bat first after the toss, like Rohit Sharma deciding based on pitch conditions, mirrors Lua's if/elseif/else, which lets a script pick exactly one branch of action based on the conditions it evaluates at that moment.
The if / elseif / else Statement
A Lua if statement evaluates its conditions in strict top-to-bottom order: the if condition first, then each elseif in sequence, stopping at the very first one that is true and skipping the rest, including any final else. If none of the conditions are true and an else clause is present, that block runs instead. Every branch of the statement shares a single closing end.
Cricket analogy: Just as an umpire runs through out/not-out/no-ball checks in strict order after a run-out appeal, Lua checks if, then each elseif, top to bottom, stopping at the first condition that evaluates true.
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
-- and/or as a ternary substitute
local status = (score >= 80) and "Pass" or "Needs Improvement"
print(status)
-- truthy check "gotcha"
local count = 0
if count then
print("count is truthy, even though it's zero")
endTruthy and Falsy Values
Lua's truthiness rule is deliberately minimal: only nil and the boolean false are considered falsy. Every other value, including the number 0, the empty string "", and an empty table {}, is truthy and will satisfy an if condition. This is a frequent source of bugs for programmers coming from Python, JavaScript, or C, where 0 and empty strings or collections are often falsy.
Cricket analogy: Just as only a 'not out' or 'run-out' ruling actually stops play, since every other umpire signal, even a mundane dot ball, keeps the game going, in Lua only nil and false count as falsy; even 0 runs like any other delivery.
Lua's truthiness rule is one of its most distinctive design choices: unlike Python, JavaScript, or C, Lua only treats nil and false as falsy. The number 0, an empty string "", and an empty table {} are all truthy. If you need to check whether a collection is 'empty', check #t == 0 or next(t) == nil explicitly; don't rely on if t then.
Using and / or for Conditional Expressions
Because Lua has no dedicated ternary operator, the idiom cond and a or b is commonly used to pick between two values based on cond. This works because and and or short-circuit: if cond is truthy, cond and a evaluates to a, and a or b then evaluates to a (assuming a is truthy); if cond is falsy, cond and a short-circuits to cond itself (falsy), so the whole expression falls through to b.
Cricket analogy: A commentator saying 'if he's fit, Kohli bats; otherwise, Rahul opens' is exactly the fit and 'Kohli' or 'Rahul' idiom in Lua, where and/or short-circuit to pick one of two values.
The cond and a or b idiom breaks whenever a itself can be false or nil, because Lua then falls through to evaluate b regardless of whether cond was true. For example, enabled and false or true always evaluates to true, even when enabled is true. Use a real if/else whenever the 'true' branch value might itself be falsy.
Nested Conditionals and Emulating a switch Statement
Deeply nested if statements, or a long elseif chain that repeatedly tests the same variable against many different values, quickly become hard to read. The idiomatic Lua replacement is a table that maps each possible value to a handler function or result: indexing the table with the tested value replaces the whole chain with a single lookup, which is both shorter and easier to extend.
Cricket analogy: Instead of a long elseif chain for every possible dismissal type, a scorer can use a lookup table keyed by 'bowled', 'caught', 'lbw', just as Lua replaces a bulky elseif ladder with a dispatch table indexed by string.
- Lua's conditional statement is
if cond then ... elseif cond2 then ... else ... end; thethenandendkeywords are mandatory and there are no curly braces. - Only
nilandfalseare falsy in Lua; every other value, including0,"", and{}, is truthy. - Lua has no built-in
switchstatement; use chainedelseifor, for many discrete cases, a table keyed by the value being tested. - The
cond and a or bidiom substitutes for a ternary operator but fails whenacan befalseornil. - Conditions are evaluated top to bottom, and execution jumps to the
endof the wholeifblock as soon as one branch runs. - Comparison operators are
==,~=(not!=),<,>,<=,>=, and the logical operators are the wordsand,or,not.
Practice what you learned
1. Which values are falsy in Lua?
2. What keyword does Lua use in place of a switch statement?
3. What is the result of `local x = false and "a" or "b"` in Lua?
4. Which keyword must terminate every if statement block in Lua?
5. Why does `enabled and false or true` fail as a way to return false when enabled is true?
Was this page helpful?
You May Also Like
Loops in Lua
A practical guide to Lua's while, repeat...until, numeric for, and generic for loops, plus how break and Lua's lack of a continue keyword affect loop control.
Functions in Lua
Learn how to define and call Lua functions, treat them as first-class values, use colon syntax for methods, and understand local vs global function scope.
Closures in Lua
Understand how Lua closures capture upvalues by reference, how to use them for private state and per-iteration loop callbacks, and common closure-based patterns like memoization.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics