Elseif Chains
Sometimes two choices are not enough. A temperature can be freezing, cold, mild or hot. To check more than one condition, add elseif branches to your if:
local temperature = 18
if temperature < 0 then
print("Freezing")
elseif temperature < 15 then
print("Cold")
elseif temperature < 25 then
print("Mild")
else
print("Hot")
end
Output:
Mild
Lua checks the conditions from top to bottom. The first true condition wins, its block runs, and Lua skips the rest. Here 18 is not below 0 and not below 15, but it is below 25, so Mild prints. The else at the end runs only when no condition was true. One end closes the whole chain.
One word: elseif
elseif is one word, and it has its own condition and its own then. If you write else if as two words, Lua sees a new if inside the else, and that new if needs its own end:
local temperature = 18
if temperature < 0 then
print("Freezing")
else if temperature < 15 then
print("Cold")
else
print("Mild")
end
Output:
/usr/bin/lua5.4: main.lua:9: 'end' expected (to close 'if' at line 2) near <eof>
The program does not run at all. If Lua says an end is missing in a chain, look for an else if written as two words.
The order matters
Look at the second condition in the first example. It is only temperature < 15, with no lower limit. It does not need one. Lua reaches that line only when the first condition was false, so the temperature is already 0 or more.
This also means a chain in the wrong order gives wrong answers. Here the < 25 check comes first:
local temperature = -5
if temperature < 25 then
print("Mild")
elseif temperature < 0 then
print("Freezing")
end
Output:
Mild
-5 is below 25, so the first branch wins and Freezing can never print. Lua shows no error for this. When a chain gives a strange answer, read it from the top and ask which values the earlier lines already caught.
In the exercise, finish an elseif chain that turns a score into a grade letter.