Logical Operators
Sometimes one condition isn't enough. “Emma goes to the market if she has at least 12 eggs and it's sunny” is made of two conditions joined by “and”. Lua uses that very word:
local eggs = 18
local weather = "sunny"
if eggs >= 12 and weather == "sunny" then
print("Emma goes to the market")
endThis prints:
Emma goes to the marketand, or and not are logical operators. They work with conditions:
a and bis true only if both parts are true;a or bis true if at least one part is true;not aturns true into false, and false into true.
Lua writes them as words. Many other languages use &&, || and !, but in Lua, && ends with unexpected symbol near '&'.
“Grandpa Joe comes to help on Saturday or Sunday”:
local day = "Sunday"
if day == "Saturday" or day == "Sunday" then
print("Grandpa Joe comes to help")
endThis prints:
Grandpa Joe comes to helpEach part must be a whole comparison. If you shorten it the way we speak, to day == "Saturday" or "Sunday", the right part is just the text "Sunday", and a text counts as true (more about that in the next exercise). The condition is then true every day, even on Monday, and Lua reports no error.
not is handy with boolean variables. Read not isRaining as “it isn't raining”:
local isRaining = false
if not isRaining then
print("Emma waters the field")
endThis prints:
Emma waters the fieldnot applies only to the value right after it. not eggs > 10 doesn't mean “not more than 10 eggs”: Lua first computes not eggs, which is false, and then compares false with 10:
local eggs = 8
if not eggs > 10 then
print("Not enough eggs")
endmain.lua:2: attempt to compare number with booleanPut the comparison in parentheses, not (eggs > 10), or simply write the opposite comparison, eggs <= 10. In a longer condition, not goes first, then and, and or last, just as multiplication goes before addition. Use parentheses to group what belongs together: (day == "Saturday" or day == "Sunday") and not isRaining.
Instructions
Emma takes the eggs to the market if she has at least 12 eggs and it isn't raining. Below the last line, write an if statement that prints Emma goes to the market in that case. Use and and not.
Add an else branch that prints Emma stays at the farm. Then change isRaining to true. One false part is enough to make the whole and condition false, so the program prints:
Eggs: 20
Emma stays at the farmOn rainy days, or when Emma has more than 30 eggs, Hugo the trader comes to the farm to buy them. Below the end, write another if statement with or that prints Hugo comes to the farm. The program prints:
Eggs: 20
Emma stays at the farm
Hugo comes to the farmStart programming for free
5/10