Records
So far, Emma's dictionaries have held many things of the same kind: crops and their counts, crops and their prices. A table can also describe one thing with several values. Such a table is often called a record, and its keys fields:
local carrot = {name = "Carrot", days = 3, seedPrice = 2, sellPrice = 5}
print(carrot.name .. " grows in " .. carrot.days .. " days.")
print("Profit: " .. (carrot.sellPrice - carrot.seedPrice) .. " coins")This prints:
Carrot grows in 3 days.
Profit: 3 coinsIt's the same kind of table as the barn, used in a different way. In the barn, the keys are the data: Emma can add any crop at any time. In a record, the keys are fixed and known in advance. Every crop has a name, days, a seedPrice and a sellPrice, and the program reads them with a dot. The values can be of different types:
local bella = {name = "Bella", kind = "cow", age = 4, milked = false}
bella.milked = true
print(bella.name, bella.kind, bella.age, bella.milked)Bella cow 4 trueRecords go well with functions. Instead of passing the name, the days and the prices one by one, you pass one record, and the function reads the fields it needs:
local function profit(crop)
return crop.sellPrice - crop.seedPrice
end
local carrot = {name = "Carrot", days = 3, seedPrice = 2, sellPrice = 5}
local potato = {name = "Potato", days = 4, seedPrice = 3, sellPrice = 8}
print(profit(carrot), profit(potato))3 5A function can also create a record and return it. When you need many records of the same shape, you write their fields only once, in the function:
local function newPlot(crop)
return {crop = crop, day = 0, watered = false}
end
local plot = newPlot("pumpkin")
print(plot.crop, plot.day, plot.watered)pumpkin 0 falsecrop = crop may look strange. On the left of = is the key, the field crop. On the right is its value: the parameter crop, which holds "pumpkin" in this call. Each call returns a new table, so every plot has its own fields.
A typical mistake is a typo in a field's name. Lua doesn't check the names of fields, so carrot.sellprice (with a lowercase p) is simply nil, and computing with it ends with attempt to perform arithmetic on a nil value (field 'sellprice'). When you see field '…' in an error, compare the name in the message with the name in the table.
Instructions
Write a function describe(crop) that returns (not prints) a text about the crop it gets, with its profit: the sell price minus the seed price. Print describe(pumpkin):
Pumpkin: 7 days, profit 15 coinsBelow, create a record strawberry with the same four fields as the pumpkin: the name "Strawberry", 5 days, seeds for 4 coins and a sell price of 12 coins. Print its description:
Strawberry: 5 days, profit 8 coinsWrite a function newCrop(name, days, seedPrice, sellPrice) that returns a new record with these four fields. Use it to create corn: 6 days, seeds for 3 coins, a sell price of 10 coins. Print its description:
Corn: 6 days, profit 7 coinsStart programming for free
6/10