16. if / elseif / else

So far, programs ran the same way every time. This chapter adds a condition: a question answered true or false. That answer decides which block of code runs.

Comparing values

Conditions are built from comparison operators. Each compares two values and returns a boolean.

Operator Meaning
== equal to
~= not equal to (note: ~, not !)
< less than
> greater than
<= less than or equal to
>= greater than or equal to
print(7 == 7)     -- true
print(7 == 8)     -- false
print("a" == "A") -- false  (case matters)
print(7 ~= 8)     -- true
print(3 < 5)      -- true
print(3 >= 3)     -- true

The equality operator is == (two equals signs). A single = is assignment — it changes a variable. So if x = 7 is a syntax error; Lua refuses to run it.

The if statement

if runs a block of code only when its condition is true.

local age = 16
if age >= 18 then
    print("You can vote.")
end

Read it left to right: if the age is at least 18, then print the message, end of the if. The indentation (usually four spaces) is for the reader; Lua does not require it, but always indent anyway — it makes mistakes easier to spot.

else for the other case

else runs when the condition is false. With if, it covers both possibilities exactly once:

local age = 16
if age >= 18 then
    print("You can vote.")
else
    print("Not old enough to vote yet.")
end

Exactly one print line runs, never both.

elseif for chains

For more than two cases, chain them with elseif. Lua tries each in order and stops at the first true one:

local score = 73
if score >= 90 then
    print("Grade: A")
elseif score >= 80 then
    print("Grade: B")
elseif score >= 70 then
    print("Grade: C")
elseif score >= 60 then
    print("Grade: D")
else
    print("Grade: F")
end

Order matters: Lua takes the first match. With score >= 60 on top, every passing grade would get a D — nobody would see A, B, or C.

Open exercises/16/01-grade.lua. Change the score and run it. Try values right at the boundaries (60, 70, 80, 90) to confirm >= includes them.

Combining conditions with and, or, not

Sometimes one comparison is not enough. Lua has three logical operators that combine booleans:

Operator Meaning
and true if both sides are true
or true if either side is true
not flips true to false and false to true
local level = 12
local has_key = true

if level >= 10 and has_key then
    print("You can enter the dungeon.")
end

if level < 10 or not has_key then
    print("You are blocked.")
end

Spell them out as words. Lua does not use &&, ||, or !.

Truthy and falsy

The conditions above all produce real booleans, but if accepts any value. Lua's rule:

  • nil and false are falsyif skips the block.
  • Everything else is truthy — including 0, "", and 0.0.

This surprises people, especially 0 being truthy. It is handy for checking whether a variable has a value:

local name = io.read()    -- could be nil if input is empty in some cases
if name then
    print("Hello, " .. name)
else
    print("No name was entered.")
end

Open exercises/16/02-truthy.lua and run it. Compare the output to what you expected. The result for 0 and "" often surprises.

Homework

Problem 1 — Even or odd

Open exercises/16/homework/01-even-or-odd.lua. Prompt for a number. Print even or odd based on whether n % 2 is 0.

Problem 2 — Roblox level gate

Open exercises/16/homework/02-level-gate.lua. Two variables sit at the top: level (a number) and has_key (a boolean). Print You can enter the dungeon. only when the player is at least level 10 and has the key. Otherwise print one of:

  • Level too low. (if the level alone is the problem),
  • Missing the key. (if the level is fine but the key is missing),
  • Level too low and missing the key. (if both are wrong).

Problem 3 — Grade letter

Open exercises/16/homework/03-grade-letter.lua. Prompt for a score (0 to 100). Print the grade letter A, B, C, D, or F using the same cutoffs as the example in this chapter.

Challenge — Largest of three

Open exercises/16/homework/04-largest-of-three.lua. Three variables hold three numbers. Print the largest, using if and the comparison operators — no loops, no tables, no math.max. The twist: handle ties cleanly (if two numbers tie for largest, print one of them).

Stuck or finished? Open the homework solutions page.