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")
end

This prints:

Emma goes to the market

and, or and not are logical operators. They work with conditions:

  • a and b is true only if both parts are true;
  • a or b is true if at least one part is true;
  • not a turns 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")
end

This prints:

Grandpa Joe comes to help

Each 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")
end

This prints:

Emma waters the field

not 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")
end
main.lua:2: attempt to compare number with boolean

Put 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 farm

On 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 farm

Start programming for free

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

Or sign up with:

5/10