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.
for i= 0, 2 do
print(array[i])
end
After we run the above code, we will get the following output.
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.
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.
-2
0
2
4
Multidimensional array
Multidimensional arrays can be implemented in two ways.
- Array of array
- One-dimensional arrays control index
For 3,3 multidimensional arrays, the example of using arrays is shown below.
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.
2
3
2
4
6
3
6
9
An example for 3,3 multidimensional arrays is shown below using the operation index.
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.
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.