Keys in Variables
The key in square brackets doesn't have to be written out. It can be in a variable, or come from a parameter or a loop:
local prices = {carrot = 5, potato = 8, strawberry = 12}
local crop = "potato"
print(prices[crop])This prints:
8Lua first looks into the variable crop, finds the text "potato" in it, and then reads the value with that key. This is how you write code for a key you don't know yet when you write the program: the crop a customer asks for, or each crop in a list.
And now the classic mistake. The dot is always followed by the key itself, never by a variable. prices.crop means prices["crop"]: the key is the text "crop", and there's no such key in the table:
local prices = {carrot = 5, potato = 8, strawberry = 12}
local crop = "potato"
print(prices.crop)
print(prices["crop"])
print(prices[crop])This prints:
nil
nil
8So: when you know the key as you write the code, use a dot (prices.potato). When the key is in a variable, use square brackets without quotes (prices[crop]). With quotes, it's just a text again: prices["crop"] is the same as prices.crop.
Keys in variables are most useful in functions and loops. This function works for any crop, even one you add to the table later:
local prices = {carrot = 5, potato = 8, pumpkin = 20}
local function priceOf(crop, amount)
return prices[crop] * amount
end
print(priceOf("carrot", 3))
print(priceOf("pumpkin", 2))This prints:
15
40If you wrote prices.crop * amount in it by mistake, the program would end with attempt to perform arithmetic on a nil value (field 'crop'). The message names the key that Lua looked for, 'crop': that's the sign that you wrote the name of the variable instead of using its value. And when the key from a variable isn't in the table, the message has a question mark instead of a name, because Lua doesn't know where the key came from: priceOf("corn", 1) ends with attempt to perform arithmetic on a nil value (field '?').
One more detail: a key can also be a number, and a number is a different key from a text. t[1] and t["1"] are two different keys.
Instructions
The program ends with an error. Fix the function priceOf so that it reads the price of the crop in the parameter crop. The program prints:
3 carrots: 15 coinsA customer has brought a list of what they want, order: one piece of each crop. At the end of the program, go through it with ipairs and print the price of each crop. Emma doesn't sell corn at her stall (she keeps it for the hens), so prices has no key "corn": for it, print corn: not for sale. The program prints:
pumpkin: 20
strawberry: 12
corn: not for sale
carrot: 5Below the loop, print how much the customer pays for the crops Emma sells:
Total: 37 coinsStart programming for free
3/10