Summary
In this lesson, you learned that:
- A table can be a dictionary:
{carrot = 12, potato = 30}holds key–value pairs. Lua has no other type for it; a list is a table whose keys are 1, 2, 3… - You read a value with a dot,
barn.carrot, or in square brackets,barn["carrot"]. A key with a space must be in brackets and quotes:["sweet corn"] = 9. - Assigning changes a value or adds a new key (
barn.eggs = 18); assigningnilremoves the key. A missing key givesnil, not an error, andbarn.pumpkin or 0turns it into a default value.#doesn't count the keys of a dictionary. - When the key is in a variable, use square brackets without quotes:
prices[crop].prices.cropis the key"crop". for key, value in pairs(t)goes through every key, in no defined order. To print in order, collect the keys into a list, sort it withtable.sortand go through it withipairs.counts[x] = (counts[x] or 0) + 1counts things; the parentheses matter.- A record is a table that describes one thing, with fixed fields:
{name = "Carrot", days = 3}. A list of records is processed withipairs: totals, filters, finding a record. - Tables can be nested:
farm.barn.eggs. Reading through a missing table ends withattempt to index a nil value (field 'shed'). - A variable holds a reference to a table: neither
local b = anor passing a table to a function copies it.{} == {}isfalse. To get a separate table, copy it withpairs.
In the next lesson, Strings, you'll work with texts: cut out parts of them, search in them, line them up in columns and take them apart into words and numbers.
Now some practice. This week, Emma kept a harvest diary: what she harvested each day, and how much.
Instructions
Write a function totals(records) that returns a dictionary: for every crop, how much of it Emma harvested in total. Then print the totals, sorted by the crop's name:
carrot: 25
potato: 35
pumpkin: 3Write a function worth(amounts, priceList) that gets the dictionary of totals and a price list, and returns how many coins the whole harvest is worth. Print:
Worth: 465 coinsFinally, print By amount: and below it the crops once more, from the largest amount to the smallest. Sort the list of crops with a comparison function that compares their totals:
By amount:
potato: 35
carrot: 25
pumpkin: 3Start programming for free
10/10