An array is a collection of elements of the same data type arranged in a certain order, which can be one-dimensional and multidimensional arrays.
The index key values of the Lua array can be represented by integers, and the size of the array is not fixed. one-dimensional arrays
A one-dimensional array is the simplest array, and its logical structure is a linear table. A one-dimensional array can be used in the for loop to the elements in a group, as follows:
Array = {"Lua", "Tutorial"} for
i= 0, 2 does
print (Array[i])
end
The results are:
Nil
Lua
Tutorial
* * As you can see, we could use an integer index to access the array element and return nil If we know the index has no value.
The Lua index value starts with 1, but you can also specify 0 to start. **
In addition we can also index values in negative numbers:
Array = {}
for i=-2, 2 does
array[i] = i *2 end for
i = -2,2 does
print (array[i))
end
Output results:
-4
-2
0
2
4
Multidimensional Arrays
A multidimensional array is an array of index keys that contain an array or a one-dimensional array.
The following is an array multidimensional array of three rows and three columns:
--Initialize array
= {} for
i=1,3 does
array[i] = {} for
j=1,3 does
array[i][j] = I*j end
--Visit Ask the array for i=1,3 do to
j=1,3 do
print (Array[i][j]
)
end
The results are as follows:
1
2
3
2
4
6 3 6 9
Three row three array multidimensional arrays of different index keys:
--Initialize array
= {}
maxRows = 3
maxcolumns = 3 for row=1,maxrows does for
col=1,maxcolumns do
array[row*maxcolumns +col] = Row*col
End
--access array
for row=1,maxrows does
for col=1, MaxColumns do
print (Array[row*maxcolumns +col])
End
Output results:
123246369
As you can see, in the above example, the array sets the specified index value, which avoids the nil value and helps conserve memory space.