The best Lua array Tutorial In 2024, In this tutorial you can learn One-dimensional array,Multidimensional Arrays,
Array is a collection of the same type of data elements in a certain order, which can be one-dimensional arrays and multidimensional arrays.
Lua array index key values can be used as an integer, the size of the array is not fixed.
One-dimensional array is an array of the most simple, logical structure is a linear form. One-dimensional array can be used for the loop elements in the array, the following examples:
array = {"Lua", "Tutorial"} for i= 0, 2 do print(array[i]) end
The output is the above code is executed:
nil Lua Tutorial
As you can see, we can use an integer index to access array elements, if you know there is no index value is returned nil.
In Lua index values are 1 start, but you can also specify 0.
Except addition, we may also be a negative array index value:
array = {} for i= -2, 2 do array[i] = i *2 end for i = -2,2 do print(array[i]) end
The output is the above code is executed:
-4 -2 0 2 4
Multidimensional array that is an array that contains an array of index key or a one-dimensional array corresponding to the array.
Here is an array of three rows and three columns in a multidimensional array:
-- 初始化数组 array = {} for i=1,3 do array[i] = {} for j=1,3 do array[i][j] = i*j end end -- 访问数组 for i=1,3 do for j=1,3 do print(array[i][j]) end end
The output is the above code is executed:
1 2 3 2 4 6 3 6 9
Three rows of three arrays multidimensional arrays different index keys:
-- 初始化数组 array = {} maxRows = 3 maxColumns = 3 for row=1,maxRows do for col=1,maxColumns do array[row*maxColumns +col] = row*col end end -- 访问数组 for row=1,maxRows do for col=1,maxColumns do print(array[row*maxColumns +col]) end end
The output is the above code is executed:
1 2 3 2 4 6 3 6 9
As you can see, the above examples, the array index is set to the specified value, so can avoid nil value, help to save memory space.