Comparison Operators
The symbols > and < are comparison operators: they compare two values. Lua has six of them:
==equal to:5 == 5~=not equal to:5 ~= 3>greater than:5 > 3<less than:3 < 5>=greater than or equal to:5 >= 5<=less than or equal to:3 <= 5
All the examples in the list are true. Watch the boundary: 12 > 12 is false, but 12 >= 12 is true. “A dozen eggs or more” is therefore eggs >= 12.
Every comparison gives a boolean, true or false, which you know from the previous lesson. You can print it, or store it in a variable:
local eggs = 12
print(eggs > 12, eggs >= 12)
local isDozen = eggs == 12
print("A dozen:", isDozen)This prints:
false true
A dozen: trueIn local isDozen = eggs == 12, Lua first compares and then stores the result. “Equal” is written with two equals signs, because one already has a job: eggs = 12 assigns (stores 12 in eggs), while eggs == 12 compares (asks whether eggs is 12, and changes nothing). A single = in a condition is a syntax error: if eggs = 12 then ends with 'then' expected near '='.
“Not equal” is ~= in Lua: a tilde and an equals sign. Many other languages write !=, which Lua doesn't know:
local day = "Monday"
if day != "Saturday" then
print("No market today")
endmain.lua:2: 'then' expected near '!'You can compare texts, too. Two texts are equal only if they match exactly, character by character: "Carrot" == "carrot" is false, because a capital letter is a different character. < and > compare texts in alphabetical order: "apple" < "banana" is true. All capital letters come before all lowercase ones, though, so "Zebra" < "apple" is true as well.
A number and a text are never equal, so 12 == "12" is false, even though Lua turns "10" + 5 into a number by itself. And <, >, <= or >= between a number and a text end with an error:
local eggs = "14"
if eggs < 12 then
print("Not enough eggs")
endmain.lua:2: attempt to compare string with numberWhen a number comes as a text, convert it with tonumber first.
Instructions
Run the program: it ends with an error. Fix the condition with the operator Lua uses for “not equal”. The program then prints:
The market is open only on Saturdays
Carrots: 15Hugo the trader buys carrots by the dozen. At the end of the program, write an if statement that prints Hugo buys a dozen carrots if carrots is 12 or more. The program prints:
The market is open only on Saturdays
Carrots: 15
Hugo buys a dozen carrotsChange carrots to 12. A dozen is exactly 12, so Hugo still buys them, and the program prints:
The market is open only on Saturdays
Carrots: 12
Hugo buys a dozen carrotsIf the last line is missing, check your comparison operator.
Start programming for free
2/10