if, elseif and else Statements
Write conditional branching logic with Lua's if/elseif/else syntax.
if, elseif and else Statements is a free Lua Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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")
endLogical Operators in Conditions
Lua uses and, or, and not as logical operators. They short-circuit: and returns the first falsy value or the last value; or returns the first truthy value or the last value. This enables idiomatic default-value patterns.
local age = 25
local hasID = true
if age >= 18 and hasID then
print("Entry allowed")
end
-- or for defaults
local name = nil
local display = name or "Guest"
print(display) -- GuestTernary Idiom with and/or
Lua has no ternary operator, but the and/or pattern approximates it: condition and trueVal or falseVal. This works as long as trueVal is not false or nil. For safer ternary logic, use an inline if function.
local x = 10
local label = (x > 5) and "big" or "small"
print(label) -- big
-- Safe ternary function
local function ternary(cond, t, f)
if cond then return t else return f end
end
print(ternary(false, "yes", "no")) -- noNested if Statements
You can nest if statements inside other branches. Each nested block requires its own end. Deep nesting often signals an opportunity to use early returns or guard clauses to flatten the logic.
local loggedIn = true
local isAdmin = false
if loggedIn then
if isAdmin then
print("Admin dashboard")
else
print("User dashboard") -- prints
end
else
print("Login required")
endGuard Clauses
A guard clause is an early return that handles invalid/edge cases at the top of a function, reducing nesting. This pattern keeps the "happy path" code unindented and easier to read.
local function processAge(age)
if type(age) ~= "number" then
return nil, "age must be a number"
end
if age < 0 then
return nil, "age cannot be negative"
end
-- happy path
return math.floor(age)
end
print(processAge(25.7)) -- 25
print(processAge(-1)) -- nil age cannot be negativeComparing Values
Lua comparison operators: == (equal), ~= (not equal), <, >, <=, >=. Note: ~= is Lua's "not equal" — not !=. String comparisons use lexicographic order. You cannot compare strings with numbers directly.
print(1 == 1) -- true
print(1 ~= 2) -- true
print("abc" < "abd") -- true (lexicographic)
print("10" == 10) -- false (different types)
-- Safe nil check
local val = nil
if val == nil then
print("no value")
endString Equality
Two strings are equal in Lua if and only if they have the same byte content and length. Lua interns strings, so equal strings often point to the same memory, making == a fast pointer comparison. Never compare strings with is or reference equality — == always compares by value.
local s1 = "hello"
local s2 = "hel" .. "lo"
print(s1 == s2) -- true (same content)
print(s1 == "Hello") -- false (case sensitive)
-- Check for empty string
local name = ""
if name == "" or name == nil then
print("name is empty or nil")
endTable and Function Comparison
Tables and functions are compared by reference, not by content. Two different table literals with identical content are not equal unless they are the same object. Use metamethods like __eq to define custom equality for tables.
local t1 = {1, 2, 3}
local t2 = {1, 2, 3}
local t3 = t1
print(t1 == t2) -- false (different objects)
print(t1 == t3) -- true (same reference)
local f1 = function() end
local f2 = function() end
print(f1 == f2) -- falseIdiomatic Patterns
Common Lua idioms with conditionals: use assert() to validate preconditions, use the and/or trick for short defaults, and avoid double-negatives (not not x) to convert any value to boolean.
-- assert pattern
local function sqrt(n)
assert(n >= 0, "sqrt of negative")
return math.sqrt(n)
end
-- Convert to boolean
local val = 42
local boolVal = not not val
print(boolVal) -- true
-- Default parameter
local function greet(name)
name = name or "World"
print("Hello, " .. name)
end
greet() -- Hello, WorldQuick Check
Which values are falsy in Lua?
Recap: Conditionals
Summary:
if ... elseif ... else ... end— the full branching form- Only
nilandfalseare falsy and/orshort-circuit and return operand values~=is "not equal" in Lua (not !=)- Tables/functions compare by reference, strings by value
- Use guard clauses to reduce nesting
Frequently asked questions
Is the “if, elseif and else Statements” lesson free?
Yes — the full text of “if, elseif and else Statements” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
What will I learn in “if, elseif and else Statements”?
Write conditional branching logic with Lua's if/elseif/else syntax. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Lua Academy?
No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “if, elseif and else Statements” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Lua Academy lesson?
Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- if, elseif and else Statements
- while and repeat-until Loops
- Numeric for Loop
- Generic for and break