Lua - Sparse Arrays



In Lua, a matrix can be implmented as a multidimensional arrays. As in lua array, 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.

A Matrix can be implemented as Multi-dimensional array in two ways.

  • Array of arrays
  • Single dimensional array by manipulating indices

Example - Create matrix using array of arrays

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

main.lua

-- initialize a matrix
matrix = {}
-- max rows
rows = 3
-- min rows
columns = 3

for i=1,rows do
    -- create a new row
    matrix[i] = {}     
    for j=1,columns do
        -- add a value to the matrix
        matrix[i][j] = i * j
    end
end

-- print the matrix
for i=1,rows do
    for j=1,columns do
        print(i,j,matrix[i][j])
    end
end

Output

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

1	1	1
1	2	2
1	3	3
2	1	2
2	2	4
2	3	6
3	1	3
3	2	6
3	3	9

Problem with the above approach is creation of multiple arrays with lot of storage. In case of sparse matrix, where lot of entries are either nil or zero, that it will be a lot of storage required. So in next approach, we'll show case a better approach to create a matrix.

Example - Creating Matrix

An example for matrix is shown below using manipulating indices.

main.lua

-- initialize a matrix
matrix = {}
-- max rows
rows = 3
-- min rows
columns = 3

for i=1,rows do
   for j=1,columns do
      matrix[i*columns + j] = i * j
   end
end

-- print the matrix
for i=1,rows do
   for j=1,columns do
      print(i,j,matrix[i*columns + j])
   end
end

Output

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

1	1	1
1	2	2
1	3	3
2	1	2
2	2	4
2	3	6
3	1	3
3	2	6
3	3	9
Advertisements