More Options: elseif

With if and else, a program chooses between two options. Often, there are more. For more options, add elseif branches, each with a condition and a then of its own:

local weather = "cloudy"
if weather == "sunny" then
    print("Water the field twice")
elseif weather == "cloudy" then
    print("Water the field once")
else
    print("No watering today")
end

This prints:

Water the field once

The program checks the conditions from top to bottom and runs the block of the first true one. It skips the rest of the branches, even if a later condition is true, too. Only if no condition is true does the else block run. You can add as many elseif branches as you need, always between the if and the else. The else is optional: without it, nothing runs when no condition is true. And however many branches there are, a single end closes them all.

Since the first true condition wins, the order matters:

local eggs = 40
if eggs >= 12 then
    print("One box of eggs for the market")
elseif eggs >= 36 then
    print("Three boxes of eggs for the market")
end

This prints:

One box of eggs for the market

40 eggs are enough for three boxes, but the first condition is already true, so the program never gets to the second one. Put the stricter condition first: eggs >= 36, then eggs >= 12.

elseif is one word. Written as two, else if means something else: an else branch with a new, separate if statement inside it, and that one needs an end of its own:

local weather = "rainy"
if weather == "sunny" then
    print("Water the field twice")
else if weather == "cloudy" then
    print("Water the field once")
else
    print("No watering today")
end
main.lua:8: 'end' expected (to close 'if' at line 2) near <eof>

The end on line 8 closes the inner if from line 4, and the outer if from line 2 is left without one. Write elseif as one word, and one end is enough.

Instructions

Run the program: it ends with an error. Fix it by writing elseif as one word. The program then prints Greenhouse: 15 °C and Close the windows.

Add one more elseif branch with the condition temperature > 20 that prints Open one window, and change temperature to 24. The program should print:

Greenhouse: 24 °C
Open one window

If it prints Close the windows, the condition temperature > 10 comes first and catches 24 °C, too: move the new branch above it.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/10