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 ascrops[0]or one past the end, givesnil, not an error. The error comes later, when you use thenil:attempt to concatenate a nil value (field '?'). #cropsis the length of the list, andcrops[#crops]is its last item.crops[2] = "tomato"changes an item, andcrops[#crops + 1] = "corn"adds one to the end. Don't leave holes (nilbetween items):#andipairsstop working reliably.table.insert(t, value)adds an item to the end, andtable.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 dogoes through all the indexes (not from 0, and not up to#crops + 1).for i, crop in ipairs(crops) dogives 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 withstring.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
11/11