Ranges

Many conditions ask whether a number lies in a range: is the temperature between 10 and 25 degrees? Does the pumpkin weigh from 4 to 8 kg? In math, you'd write 10 ≤ t ≤ 25. In Lua, you need two comparisons joined with and:

local temperature = 18
if temperature >= 10 and temperature <= 25 then
    print("The hens are comfortable")
end

This prints:

The hens are comfortable

Each part is a whole comparison with temperature in it. The math notation doesn't work, and its error may puzzle you:

local temperature = 18
if 10 <= temperature <= 25 then
    print("The hens are comfortable")
end
main.lua:2: attempt to compare boolean with number

Lua compares from left to right: 10 <= temperature gives true, and then it tries true <= 25, a boolean with a number. The opposite, “outside the range”, needs or: temperature < 10 or temperature > 25. With and, it would never be true, because no number is below 10 and above 25 at the same time.

When you split numbers into several ranges, use elseif. Each elseif runs only when all the conditions above it were false, so it doesn't have to repeat them:

local weight = 6
if weight < 4 then
    print("Small pumpkin: 10 coins")
elseif weight <= 8 then
    print("Medium pumpkin: 20 coins")
else
    print("Large pumpkin: 35 coins")
end

This prints:

Medium pumpkin: 20 coins

The program gets to weight <= 8 only when weight < 4 is false, so weight >= 4 and weight <= 8 isn't needed. Mind the boundaries: a pumpkin of 4 kg is medium, one of 8 kg is still medium, and else takes everything above 8. Every number should fall into exactly one range: with weight < 4 and weight > 4, a pumpkin of exactly 4 kg would fall through the gap between them.

Ranges combine with other conditions. How Emma waters the field depends on the weather and on the temperature:

local weather = "sunny"
local temperature = 31
if weather == "rainy" then
    print("No watering today")
elseif temperature >= 30 then
    print("Water in the morning and in the evening")
elseif temperature >= 15 then
    print("Water in the evening")
else
    print("Water every other day")
end

This prints:

Water in the morning and in the evening

Instructions

Run the program: it ends with an error. Fix the condition with and. The program then prints:

Henhouse: 18 °C
The hens are comfortable

Add two more branches with elseif and else: below 10 °C, print Turn on the lamp in the henhouse, and above 25 °C, print Open the henhouse windows. Then change temperature to 31. The program prints:

Henhouse: 31 °C
Open the henhouse windows

Check a boundary: change temperature to 10. At 10 °C, the hens are still comfortable, so the program prints:

Henhouse: 10 °C
The hens are comfortable

If it prints Turn on the lamp in the henhouse, look at < and <= in your conditions.

Start programming for free

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

Or sign up with:

9/10