Lua array
An array is a collection of elements of the same data type arranged in a certain order, which can be an one-dimensional array and a multi-dimensional array.
The index key value of an Lua array can be expressed as an integer, and the size of the array is not fixed.
One-dimensional array
One-dimensional array is the simplest array, and its logical structure is linear table. An one-dimensional array can be used for
loop out the elements in the array, as an example:
Example
array = {"Lua", "Tutorial"}
for i= 0, 2 do
print(array[i])
end
The output of the above code execution is as follows:
nil
Lua
Tutorial
As you can see, we can use an integer index to access the array elements andreturn if the known index has no value nil
.
In Lua
index value starts with 1, but you can also specify 0 to start.
In addition, we can also use negative numbers as array index values:
Example
array = {}
for i= -2, 2 do
array[i] = i *2
end
for i = -2,2 do
print(array[i])
end
The output of the above code execution is as follows:
-4
-2
0
2
4
Multidimensional array
A multi-dimensional array is an array corresponding to the index key of an array that contains an array or an one-dimensional array.
The following is an array multidimensional array of three rows and three columns:
Example
-- Initialize array
array = {}
for i=1,3 do
array[i] = {}
for j=1,3 do
array[i][j] = i*j
end
end
-- Accessing Arrays
for i=1,3 do
for j=1,3 do
print(array[i][j])
end
end
The output of the above code execution is as follows:
1
2
3
2
4
6
3
6
9
Three-row, three-column array multidimensional array of different index keys:
Example
-- Initialize array
array = {}
maxRows = 3
maxColumns = 3
for row=1,maxRows do
for col=1,maxColumns do
array[row*maxColumns +col] = row*col
end
end
-- Initialize array
for row=1,maxRows do
for col=1,maxColumns do
print(array[row*maxColumns +col])
end
end
The output of the above code execution is as follows:
1
2
3
2
4
6
3
6
9
As you can see, in the above example, the array sets the specified index value to avoid the occurrence of nil
value, which helps to save memory space.