17. Boolean logic in depth — Homework solutions
The .lua solution files are in
exercises/17/homework/solutions/.
Problem 1 — Default colour
Problem. Fall back to "blue" when
fav is nil.
Worked solution.
local fav = nil -- try a real colour here too
local colour = fav or "blue"
print("Your colour is " .. colour)With fav = nil it prints
Your colour is blue; with fav = "red" it
prints Your colour is red.
Common mistakes.
- Writing
if fav == nil then colour = "blue" else colour = fav end. Correct, butfav or "blue"is the shorter idiom worth knowing.
Problem 2 — Truthy table
Problem. Show whether each value is truthy using
not not value.
How to think about it. One not gives
the opposite boolean; a second not flips it back,
leaving a boolean that matches the value's truthiness.
Worked solution.
print(0, not not 0) -- 0 true
print("", not not "") -- true
print(nil, not not nil) -- nil false
print(false, not not false) -- false false
print("hi", not not "hi") -- hi trueThe two surprises are 0 and "": both are
truthy in Lua.
Problem 3 — Guarded division
Problem. Print the average only when
count is above zero.
Worked solution.
local total = 90
local count = 0 -- try a real number too
if count > 0 and total / count > 0 then
print("Average: " .. (total / count))
else
print("no data")
endWith count = 0 the count > 0 test is
false, so Lua short-circuits and skips the division, printing
no data. With count = 3 it prints
Average: 30.0.
Common mistakes.
- Writing
if total / count ...without thecount > 0guard. The division then runs even whencountis0— with integer division that is an error. The guard prevents it.
Challenge — First value that exists
Problem. Print the first of a,
b, c that is not nil.
Worked solution.
local a = nil
local b = nil
local c = "third"
print(a or b or c or "none") -- thirdor runs left to right and returns the first truthy
value, so the chain lands on the first variable holding something. If
all three are nil, it returns the final
"none".
Common mistakes.
- A long
if/elseifladder checking each fornil. Correct, but theorchain does it in one line.
Done?
You now know that and/or return values,
short-circuit, and power the x or default trick. Next is
Loops, the other way to make a program do more than the
same thing each time.