Tables Inside Tables
A table can hold any kind of value, and that includes other tables. A table inside another table is called a nested table. Two shapes are very common: grids and records.
A grid
A grid is a list of rows, and each row is itself a list:
local grid = {
{1, 2, 3},
{4, 5, 6}
}
print(grid[2][3])
Output:
6
Read grid[2][3] from left to right. grid[2] is the second row, the table {4, 5, 6}. Then [3] takes the third value of that row, which is 6. So the first index is the row, and the second is the column.
To visit every value, use nested loops: the outer loop goes over the rows, and the inner loop goes over the columns of one row.
for row = 1, #grid do
for col = 1, #grid[row] do
print(row, col, grid[row][col])
end
end
Output:
1 1 1
1 2 2
1 3 3
2 1 4
2 2 5
2 3 6
A record
A record is a dictionary that describes one thing. This player has a name and a list of scores:
local player = {
name = "Alice",
scores = {90, 75, 82}
}
print(player.name)
print(player.scores[2])
print(#player.scores)
Output:
Alice
75
3
player.scores is the inner list, so player.scores[2] is its second value. You can chain dots and brackets like this, one step at a time.
A list of records is also very common, for example one record per player:
local players = {
{name = "Alice", score = 90},
{name = "Bob", score = 75}
}
for _, p in ipairs(players) do
print(p.name, p.score)
end
Output:
Alice 90
Bob 75
Create the inner table first
When you build a grid in code, each row must be a table before you can put values in it. This fails:
local grid = {}
grid[1][1] = 5
Output:
/usr/bin/lua5.4: main.lua:2: attempt to index a nil value (field 'integer index')
grid[1] is nil, because nothing was stored there yet, and you cannot index nil. The fix is to create the row first:
local grid = {}
grid[1] = {}
grid[1][1] = 5
print(grid[1][1])
Output:
5
In the exercise, read six numbers into a grid of 2 rows and 3 columns, then print the sum of each row.