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); assigning nil removes the key. A missing key gives nil, not an error, and barn.pumpkin or 0 turns 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.crop is 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 with table.sort and go through it with ipairs.
  • counts[x] = (counts[x] or 0) + 1 counts 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 with ipairs: totals, filters, finding a record.
  • Tables can be nested: farm.barn.eggs. Reading through a missing table ends with attempt to index a nil value (field 'shed').
  • A variable holds a reference to a table: neither local b = a nor passing a table to a function copies it. {} == {} is false. To get a separate table, copy it with pairs.

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: 3

Write 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 coins

Finally, 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: 3

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

10/10