Lua Arrays
An array is a collection of elements of the same data type arranged in a specific order, which can be either one-dimensional or multi-dimensional.
Lua arrays can use integer indices, and their size is not fixed.
One-Dimensional Array
A one-dimensional array is the simplest array, with a linear table as its logical structure. A one-dimensional array can be iterated through using a for loop, as shown in the following example:
Example
array = {"Lua", "Tutorial"}
for i= 0, 2 do
print(array[i])
end
The above code outputs the following results:
nil
Lua
Tutorial
As you can see, we can access array elements using integer indices. If the specified index has no value, it returns nil.
In Lua, the index values start from 1, but you can also specify 0 as the starting point.
Additionally, we can use negative numbers as array indices:
Example
array = {}
for i= -2, 2 do
array[i] = i *2
end
for i = -2,2 do
print(array[i])
end
The above code outputs the following results:
-4
-2
0
2
4
Multi-Dimensional Array
A multi-dimensional array is an array that contains arrays or a one-dimensional array where the index key corresponds to an array.
The following is a 3x3 multi-dimensional array:
Example
-- Initialize the array
array = {}
for i=1,3 do
array[i] = {}
for j=1,3 do
array[i][j] = i*j
end
end
-- Access the array
for i=1,3 do
for j=1,3 do
print(array[i][j])
end
end
The above code outputs the following results:
1
2
3
2
4
6
3
6
9
A 3x3 multi-dimensional array with different index keys:
Example
-- Initialize 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
-- Access the array
for row=1,maxRows do
for col=1,maxColumns do
print(array[row*maxColumns +col])
end
end
The above code outputs the following results:
1
2
3
2
4
6
3
6
9
As you can see, in the above examples, the array is initialized with specified index values, which avoids the occurrence of nil values and helps save memory space.