Lua - Multidimensional Lists



A multidimensional list can be implemented in Lua as a table of tables. A table in Lua is a versatile data structure and we can store any Lua object in a table even a table as well. This nesting capability allows Lua to create multidimensional lists.

Creating a multidimensional List

We can initialize a Multidimensional list during declaration as shown below −

main.lua

-- Initializing a list as 2 x 3 matrix
local matrix = {
   {1, 2, 3},
   {4, 5, 6}
}

-- Accessing the list
-- using multiple indexes
print(matrix[1][1])  -- prints 1, row 1, column 1
print(matrix[2][1])  -- prints 4, row 2, column 1

Output

When we run the above code, we will get the following output−

1
4

Dynamically initializing a multidimensional List

We can create a Multidimensional list dynamically as well as shown below−

main.lua

-- create an empty matrix
local matrix = {}

-- initialize matrix as 2 x 2 
for i= 1, 2 do
   matrix[i] = {} -- create a new row
   for j = 1, 2 do
      matrix[i][j] = i * 10 + j
   end
end

-- Accessing the list
-- using multiple indexes
print(matrix[1][1])  -- prints 1, row 1, column 1
print(matrix[2][1])  -- prints 4, row 2, column 1

Output

When we run the above code, we will get the following output−

11
21

Iterating through Multidimensional list

We can iterate a Multidimensional list using nested loops −

main.lua

-- Initializing a list as 2 x 3 matrix
local matrix = {
   {1, 2, 3},
   {4, 5, 6}
}

-- iterate rows
for i = 1, #matrix do 
   -- iterate through columns of the current row
   for j = 1, #matrix[i] do 
      print(string.format("Element at [%d][%d]: %d", i, j, matrix[i][j]))
   end
end

Output

When we run the above code, we will get the following output−

Element at [1][1]: 1
Element at [1][2]: 2
Element at [1][3]: 3
Element at [2][1]: 4
Element at [2][2]: 5
Element at [2][3]: 6

Iterating through 3 dimensional list

In similar fashion, we can iterate a 3d list using nested loops −

main.lua

-- Initializing 3d list
local threeDList = {
   {
      {1, 2},
      {3, 4}
   },
   {
      {5, 6},
      {7, 8}
   }
}

-- iterate through first dimension
for i = 1, #threeDList do 
   -- iterate through second dimension
   for j = 1, #threeDList[i] do
      -- iterate through third dimension
      for k = 1, #threeDList[i][j] do   
         print(string.format("Element at [%d][%d][%d]: %d", i, j, k, threeDList[i][j][k]))
      end
   end
end

Output

When we run the above code, we will get the following output−

Element at [1][1][1]: 1
Element at [1][1][2]: 2
Element at [1][2][1]: 3
Element at [1][2][2]: 4
Element at [2][1][1]: 5
Element at [2][1][2]: 6
Element at [2][2][1]: 7
Element at [2][2][2]: 8
Advertisements