Lua Nested Tables
A nested table is a table stored inside a slot of another table. This lets one table hold a whole grid of values.
Two indexes reach one cell
Each row is an inner table inside the grid. Two indexes in a row pick the row first and then the column.
local grid = {{1, 2, 3}, {4, 5, 6}}
print(grid[2][3])
print(grid[1][2])
print(grid[2][1])Inner tables hold their own fields
Each person is an inner table with named fields. The prints read fields from both inner tables.
local people = {{name = "Sam", age = 12}, {name = "Ana", age = 14}}
print(people[1].name)
print(people[2].name)
print(people[2].age)One inner value can change
Assigning through both indexes changes a single inner slot. The other values in the same row stay the same.
local grid = {{1, 2, 3}, {4, 5, 6}}
grid[1][2] = 20
print(grid[1][1])
print(grid[1][2])
print(grid[1][3])Example
local register = {
{name = "Sam", score = 80},
{name = "Ana", score = 95},
{name = "Lee", score = 70}
}
for i = 1, #register do
print(register[i].name .. ": " .. register[i].score)
endKey points
- Nested table: A nested table is a table stored as a value inside another table.
- Grid: A grid table holds inner tables as its rows.
- Double index: Write grid[row][col] to read a value from a row and a column.
- List of records: A table can hold several inner tables, each with its own fields.
- Update: Assigning to grid[row][col] changes only that inner value.
In this example, register holds three inner tables and each inner table stores a name and a score. The loop walks the outer table in order. Each print first picks a student with register[i] and then reads the name or score field.
Note
Each extra level of table adds one more pair of brackets to reach a value.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
With local grid = {{1, 2}, {3, 4}}, what does print(grid[2][1]) show?