🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Elseif

An elseif branch adds another condition to test inside an if statement. One statement can then choose between many outcomes instead of just two.

Grade bands pick one letter

The score of 65 fails the A and B checks and passes the C check. The chain prints C and stops testing.

local score = 65
if score >= 90 then
  print("A")
elseif score >= 75 then
  print("B")
elseif score >= 50 then
  print("C")
else
  print("F")
end

A size picker works through the bands

The length of 25 is too big for the small band and fits the middle band. The chain prints M.

local length = 25
if length <= 20 then
  print("S")
elseif length <= 30 then
  print("M")
else
  print("L")
end

The first true branch wins

The number 80 passes both the over 50 check and the over 10 check. Only the first matching label prints, which proves the order.

local number = 80
if number > 50 then
  print("Over 50")
elseif number > 10 then
  print("Over 10")
else
  print("Small")
end

Example

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
print("Score: " .. score)

Key points

  • Order: the conditions in the chain are tested from first to last.
  • First win: the first branch whose condition is true runs, and the rest are skipped.
  • Else catch: a final else runs when no condition in the chain was true.
  • One end: the whole chain still closes with a single end.
  • Bands: elseif suits ranges that sit side by side, such as grade bands.

In this example, the score of 73 is tested against the grade bands from the top down. It misses the A and B bands and lands in the C band, so that branch prints the grade. The last line sits after the single end, so it always prints the score.

Note

Lua writes elseif as one word, not as else if.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when two conditions in an elseif chain are both true?