Multi-Dimensional Lists in Lua

Since lists can contain any type as elements, they can also contain other lists. This allows multi-dimensional lists, sometimes called "matrices", to be created.

A multi-dimensional list can be created directly as before:

-- initialize a table with values

local x = {
{ "a", "b", "c" },
{ "d", "e", "f" },
{ "g", "h", "i" },
}

Now, when we access the direct descendants of this list we get the nested list. We can access the nested elements themselves by indexing the nested lists:

-- access values stored in the table

print(x[1]) -- table: 0x5e35821553e0

print(x[1][1]) -- a
print(x[1][2]) -- b
print(x[1][3]) -- c

We can also create multi-dimensional lists programmatically as well. In this example we create the list and add elements in a loop:

-- initialize an empty list

local x = {}

for i = 1, 3 do
-- instantiate an empty list to contain the nested content
local inner = {}

for j = 1, 3 do
inner[j] = string.char(97 + 3 * (i - 1) + (j - 1))
end

x[i] = inner
end

This makes use of the string.char function to generate characters from their decimal ASCII codes.

After the list is created, its elements can be accessed as usual:

-- access values stored in the table

print(x[1][1]) -- a
print(x[1][2]) -- b
print(x[1][3]) -- c

print(x[2][1]) -- d
print(x[2][2]) -- e
print(x[2][3]) -- f

print(x[3][1]) -- g
print(x[3][2]) -- h
print(x[3][3]) -- i