Default Values
and and or can do more than join conditions. They don't just give true or false: they give one of their two values. a or b gives a if a counts as true, and b otherwise:
print(nil or "friend")
print("Emma" or "friend")
print(0 or 12)This prints:
friend
Emma
0That makes or perfect for a default value: a value to use when a variable is nil. Hugo the trader may tell Emma his price for a pumpkin, or he may not:
local hugoPrice
local price = hugoPrice or 20
print("Price of a pumpkin: " .. price)This prints:
Price of a pumpkin: 20hugoPrice is nil, so price gets the default, 20. If Hugo had said 25, price would be 25. Read it as “Hugo's price, or else 20”. But remember the last line of the first example: or replaces only nil and false. 0 counts as true, so 0 or 12 is 0.
Lua does or last, after all the other operators, .. included. In a longer expression, put it in parentheses: "Price: " .. (hugoPrice or 20). Without them, "Price: " .. hugoPrice or 20 first tries to join the text with nil, and ends with the error attempt to concatenate a nil value (local 'hugoPrice').
a and b works the other way around: if a counts as false, it gives a, and otherwise b. Together, condition and x or y gives x when the condition is true and y when it isn't, like a small if with else in one line:
local eggs = 14
local box = eggs >= 12 and "a full box" or "half a box"
print("Emma packs " .. box)This prints:
Emma packs a full boxThe comparison is true, so eggs >= 12 and "a full box" gives "a full box", and "a full box" or "half a box" gives "a full box", because a text counts as true. With 8 eggs, the comparison would give false, false and … would give false, and false or "half a box" would give "half a box".
This trick fails when the value in the middle is false or nil:
local isRaining = true
local needsWater = isRaining and false or true
print(needsWater)This prints:
trueIt's raining, so the field shouldn't need water. But isRaining and false gives false, and false or true gives true. Use condition and x or y only when x can't be false or nil, such as a text or a number. Otherwise, write an if with else (or here, simply not isRaining).
Instructions
Run the program: it ends with an error, because customer is nil. Use or so that the program thanks a customer without a name as friend. The program then prints:
Eggs: 6
Thank you, friend!An egg costs 3 coins, but a customer who buys 10 or more eggs pays only 2 coins for each. Between the two print lines, create a local variable pricePerEgg that is 2 when eggs is at least 10, and 3 otherwise. Write it in one line with and and or. Then print the price of all the eggs. The program prints:
Eggs: 6
Price: 18 coins
Thank you, friend!Grandpa Joe comes to buy 10 eggs: change customer to "Grandpa Joe" and eggs to 10. The program prints:
Eggs: 10
Price: 20 coins
Thank you, Grandpa Joe!Start programming for free
7/10