Tables as Lists
So far, each variable has held one value. To keep many values together, like a list of scores, Lua has the table. Tables are the only data structure Lua has. Lists, dictionaries and records are all tables. This lesson uses a table as a list.
local scores = {90, 75, 82}
print(scores[1])
print(scores[3])
print(#scores)
Output:
90
82
3
Curly braces { } create a table. The values go inside, separated by commas. To get one value back, write the table name, then its position in square brackets. This position is called the index.
In Lua, the first index is 1, not 0. Many other languages start at 0, so if you have used one of them, be careful here.
index: 1 2 3
+----+----+----+
scores: | 90 | 75 | 82 |
+----+----+----+
# gives the length of the table, the same # you used for the length of a string.
Missing values are nil
local scores = {90, 75, 82}
print(scores[0])
print(scores[4])
Output:
nil
nil
There is no value at index 0 or index 4, so you get nil. There is no error. If a table value is nil when you did not expect it, check the index first. Writing [0] for the first value is a common mistake.
Change and add values
local scores = {90, 75, 82}
scores[2] = 78
scores[#scores + 1] = 95
print(scores[2], scores[4])
print(#scores)
Output:
78 95
4
Each slot works like a variable, so scores[2] = 78 replaces 75 with 78. A table can also grow. #scores is 3, so scores[#scores + 1] is scores[4], the slot just after the end. Putting a value there adds it to the list, and the length becomes 4.
Fill a table in a loop
{} with nothing inside is an empty table. You can fill it with a for loop, using the loop counter as the index. A second loop then reads the values back, from index 1 to #squares.
local squares = {}
for i = 1, 4 do
squares[i] = i * i
end
for i = 1, #squares do
print(i, squares[i])
end
Output:
1 1
2 4
3 9
4 16
This is the usual way to work with a list in Lua: build it in one loop, then use it in another.
In the exercise, read five numbers into a table, then print the first one, the last one and the count.