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 is the simplest array, and its logical structure is linear table. An one-dimensional array can be used The output of the above code execution is as follows: As you can see, we can use an integer index to access the array elements andreturn if the known index has no value In In addition, we can also use negative numbers as array index values: The output of the above code execution is as follows: 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: The output of the above code execution is as follows: Three-row, three-column array multidimensional array of different index keys: The output of the above code execution is as follows: As you can see, in the above example, the array sets the specified index value to avoid the occurrence of 4.20.1. One-dimensional array #
for
loop out the elements in the array, as an example:Example #
array = {"Lua", "Tutorial"}
for i= 0, 2 do
print(array[i])
end
nil
Lua
Tutorial
nil
.
Lua
index value starts with 1, but you can also specify 0 to start.Example #
array = {}
for i= -2, 2 do
array[i] = i *2
end
for i = -2,2 do
print(array[i])
end
-4
-2
0
2
4
4.20.2. Multidimensional array #
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
1
2
3
2
4
6
3
6
9
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
1
2
3
2
4
6
3
6
9
nil
value, which helps to save memory space.