Booleans, Comparisons and nil
A boolean is a value that is either true or false. You get booleans when you compare values:
local age = 20
print(age > 18)
print(age == 21)
print(age ~= 21)
Output:
true
false
true
== asks "are these equal?". Note the two = signs: one = gives a variable a value, two compare. ~= means "not equal". Many other languages write !=, but Lua uses ~=. The other comparisons are <, >, <= and >=.
Comparisons work on strings too. Upper and lower case letters are different, so "Lua" == "lua" is false.
nil
nil is Lua's value for "nothing here". You saw it in the variables lesson: a name with no value holds nil. You can check for it with ==:
local owner
print(owner)
print(owner == nil)
Output:
nil
true
local owner without a value declares the variable and leaves it nil.
Printing booleans and nil with ..
.. turns numbers into text, but it does not do this for booleans or nil:
local isAdult = 20 >= 18
print("Adult: " .. isAdult)
Output:
/usr/bin/lua5.4: main.lua:2: attempt to concatenate a boolean value (local 'isAdult')
Use tostring, which you met in the strings lesson, to turn the value into text first:
local isAdult = 20 >= 18
print("Adult: " .. tostring(isAdult))
Output:
Adult: true
What counts as false
In the next section, if will run code only when a value counts as true. Lua's rule for this is short: only false and nil count as false. Every other value counts as true, even the number 0 and the empty string "". Many other languages treat 0 as false, so keep this rule in mind. To check whether a number is zero, compare it: count == 0.
In the exercise, fill in the comparison operators to check a shop's visitor count and its owner.