Lua array
An array is a collection of elements of the same data type arranged in a certain order. It can be a one-dimensional array or a multi-dimensional array.
The index key value of Lua array can be represented by 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 a linear table. One-dimensional arrays can use for to loop out the elements in the array, as shown in the following example:
array = {"Lua", "Tutorial"} for i= 0, 2 do print(array[i]) end
The output result of the execution of the above code is:
nil Lua Tutorial
array = {} for i= -2, 2 do array[i] = i *2 end for i = -2,2 do print(array[i]) endThe above code execution output result is:
-4 -2 0 2 4
Multidimensional array A multi-dimensional array means that the array contains an array or the index key of a one-dimensional array corresponds to an array. The following is a three-row, three-column array multi-dimensional 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 endThe above code execution output result is:
1 2 3 2 4 6 3 6 9A three-row, three-column array multi-dimensional array with 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 endThe output result of the execution of the above code is:
1 2 3 2 4 6 3 6 9As you can see, in the above example, the array is set to the specified index value, which can avoid nil values. Helps save memory space.