Summary

In this lesson, you learned that:

  • A table is the only way Lua has to group values. A table that holds values in order is a list: local crops = {"carrot", "potato"}. An empty list is {}.
  • Indexes start at 1: crops[1] is the first item. An index with no item, such as crops[0] or one past the end, gives nil, not an error. The error comes later, when you use the nil: attempt to concatenate a nil value (field '?').
  • #crops is the length of the list, and crops[#crops] is its last item.
  • crops[2] = "tomato" changes an item, and crops[#crops + 1] = "corn" adds one to the end. Don't leave holes (nil between items): # and ipairs stop working reliably.
  • table.insert(t, value) adds an item to the end, and table.insert(t, position, value) inserts it at a position and moves the rest to the right. table.remove(t) removes the last item, table.remove(t, position) the item at a position, and both return the removed item.
  • for i = 1, #crops do goes through all the indexes (not from 0, and not up to #crops + 1). for i, crop in ipairs(crops) do gives you the index and the item in each iteration, and _ stands for a value you don't need.
  • print(crops) prints only the table's address, table: 0x…. table.concat(crops, ", ") joins texts and numbers into one text, with the separator between them.
  • Patterns with lists: the sum (start at 0 before the loop, print after the loop), the average (total / #t, always a decimal number, rounded with string.format("%.1f", …)) and the largest or smallest value (start with the first item, and keep its index if you need to know where it is).
  • table.sort(t) sorts numbers from the smallest, and texts by character codes, with capital letters before small ones. It changes the list and returns nothing.

In the next lesson, on functions, you'll learn to write your own functions, and with them, sort a list in any order you like. But first, practice what you know on Emma's tomato harvest.

Instructions

Two more days have passed. Add 8 and 5 to the end of harvest, and then print the whole list with table.concat: Harvest: 6, 9, 4, 11, 7, 8, 5.

Print the total and the average, with one decimal place: Total: 50 kg, average: 7.1 kg.

Find the best day, and print its number (its index) and how much Emma picked on it: Best day: 4 (11 kg).

Finally, sort harvest and print it: Sorted: 4, 5, 6, 7, 8, 9, 11.

Start programming for free

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

Or sign up with:

11/11