Nested Conditions
A block can contain any code, even another if statement. An if inside the block of another if is called a nested condition. It's useful when one question only makes sense after another. Before planting, Emma first checks whether she has any seeds, and only then looks at the weather:
local hasSeeds = true
local weather = "sunny"
if hasSeeds then
if weather == "rainy" then
print("Emma plants, and the rain waters the seeds")
else
print("Emma plants and waters the seeds")
end
else
print("Emma buys seeds first")
endThis prints:
Emma plants and waters the seedsThe inner if statement runs only when hasSeeds is true. Its blocks are indented by 4 more spaces, 8 in total, and each else and end is indented as much as the if it belongs to. Lua itself doesn't look at the indentation, though: each end closes the nearest if that is still open. The first end closes the inner if, the second one the outer if. If you forget the inner end here, Lua reports main.lua:8: 'end' expected (to close 'if' at line 4) near 'else': before the else on line 8, the if from line 4 should have been closed.
Nested conditions can often be written with and and elseif instead. This code does the same:
local hasSeeds = true
local weather = "sunny"
if hasSeeds and weather == "rainy" then
print("Emma plants, and the rain waters the seeds")
elseif hasSeeds then
print("Emma plants and waters the seeds")
else
print("Emma buys seeds first")
endThis prints:
Emma plants and waters the seedsThe program gets to elseif hasSeeds only when the first condition is false. With seeds, that means it isn't raining. Neither way is wrong: pick the one that's easier to read. When neither if has an else, though, a single if with and is almost always clearer: if hasSeeds and weather == "rainy" then instead of two if statements and two ends.
Instructions
At the market, Emma sells a box of eggs if she has at least 12 eggs, and otherwise only milk from Bella the cow. Inside the if block, below its print, add a nested if statement: if eggs is at least 12, print She sells a box of eggs; otherwise, print She sells only milk. The program prints:
Day: Saturday, eggs: 8
Emma goes to the market
She sells only milkChange eggs to 20 and run the program. Now both conditions are true:
Day: Saturday, eggs: 20
Emma goes to the market
She sells a box of eggsStart programming for free
8/10