SoFunction
Updated on 2025-03-10

Detailed explanation of array concept knowledge in Lua

An array is a device for ordered objects, which can be a single two-dimensional array containing rows or a collection of multi-dimensional arrays containing multiple rows and columns.

In Lua, arrays are implemented using index tables and integers. The size of the array is not fixed, it can grow based on the memory constraints we need.
One-dimensional array

One-dimensional arrays can be represented by a simple table structure, can be initialized, and read using a simple for loop. As shown in the following example.

Copy the codeThe code is as follows:
array = {"Lua", "Tutorial"}

for i= 0, 2 do
   print(array[i])
end

After we run the above code, we will get the following output.

Copy the codeThe code is as follows:
nil
Lua
Tutorial

As seen in the above code, when we try to access elements in an array that does not exist in the index, nil is returned. The Lua index usually starts at index 1, but it is possible to create objects at index 0 and less than 0. Show the array using negative index below we initialize the array using for loop.

Copy the codeThe code is as follows:
array = {}

for i= -2, 2 do
   array[i] = i *2
end

for i = -2,2 do
   print(array[i])
end

After we run the above code, we will get the following output.

Copy the codeThe code is as follows:
-4
-2
0
2
4

Multidimensional array

Multidimensional arrays can be implemented in two ways.

  1. Array of array
  2. One-dimensional arrays control index

For 3,3 multidimensional arrays, the example of using arrays is shown below.

Copy the codeThe code is as follows:
-- Initializing the array
array = {}
for i=1,3 do
   array[i] = {}
      for j=1,3 do
         array[i][j] = i*j
      end
end

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

After we run the above code, we will get the following output.

Copy the codeThe code is as follows:
1
2
3
2
4
6
3
6
9

An example for 3,3 multidimensional arrays is shown below using the operation index.

Copy the codeThe code is as follows:
-- Initializing the array
array = {}
maxRows = 3
maxColumns = 3
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

After we run the above code, we will get the following output.

Copy the codeThe code is as follows:
1
2
3
2
4
6
3
6
9

As seen in the example above, the data is stored based on indexes. It is also possible to use elements in a sparse way, which is a matrix working way of lua implementation. Because it is not saved in Lua zero value, it can save a lot of memory, and any special technology in Lua is used in other programming languages.