Lua - Multidimensional Arrays



Arrays are ordered arrangement of objects, which may be a one-dimensional array containing a collection of rows or a multi-dimensional array containing multiple rows and columns.

In Lua, arrays are implemented using indexing tables with integers. The size of an array is not fixed and it can grow based on our requirements, subject to memory constraints.

Multi-dimensional arrays can be implemented in two ways.

  • Array of arrays
  • Single dimensional array by manipulating indices

Example - Create Array

An example for multidimensional array of 3. 3 is shown below using array of arrays.

main.lua

-- Initializing the array
array = {}

-- loop from 1 to 3
for i=1,3 do
   array[i] = {}
   -- loop from 1 to 3	
   for j=1,3 do
      array[i][j] = i*j
   end	
end

-- Accessing the array
-- using multiple indexes
for i=1,3 do
   for j=1,3 do
      print(array[i][j])
   end
end

Output

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

1
2
3
2
4
6
3
6
9

Example - Creating Indices

An example for multidimensional array is shown below using manipulating indices.

main.lua

-- Initializing the array
array = {}

-- set maximum rows and columns
maxRows = 3
maxColumns = 3

-- loop from 1 to maxRows and maxColumns
for row=1,maxRows do
   for col=1,maxColumns do
      array[row*maxColumns +col] = row*col
   end	
end

-- Accessing the array
for row=1,maxRows do
   for col=1,maxColumns do
      print(array[row*maxColumns +col])
   end	
end

Output

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

1
2
3
2
4
6
3
6
9

As you can see in the above example, data is stored based on indices. It is possible to place the elements in a sparse way and it is the way Lua implementation of a matrix works. Since it does not store nil values in Lua, it is possible to save lots of memory without any special technique in Lua as compared to special techniques used in other programming languages.

Advertisements