English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
An array is a collection of elements of the same data type arranged in a certain order, which can be a one-dimensional array or a multidimensional array.
Lua array index keys can be represented by integers, and the size of the array is not fixed.
One-dimensional arrays are the simplest arrays, with a logical structure of a linear table. One-dimensional arrays can iterate over the elements of the array using a for loop, as shown in the following example:
array = {"Lua", "Tutorial"} for i= 0, 2 do print(array[i]) end
The output result of the above code is as follows:
nil Lua Tutorial
As you can see, we can use integer indices to access array elements, and if the known index has no value, it returns nil.
In Lua, index values are based on 1 as the starting point, but you can also specify starting from 0.
In addition, we can also use negative numbers as array index values:
array = {} for i= -2, 2 do array[i] = i *2 end for i = -2,2 do print(array[i]) end
The output result of the above code is as follows:
-4 -2 0 2 4
Multidimensional arrays are arrays that contain arrays or one-dimensional arrays, where the index keys correspond to an array.
Here is a three-row, three-column array of arrays:
-- Initialize the array array = {} for i=1,3 do array[i] = {} for j=1,3 do array[i][j] = i*j end end -- Access the array for i=1,3 do for j=1,3 do print(array[i][j]) end end
The output result of the above code is as follows:
1 2 3 2 4 6 3 6 9
A three-row, three-column array of arrays with different index keys:
-- Initialize the array array = {} maxRows = 3 maxColumns = 3 for row=1,maxRows do for col=1,maxColumns do array[row*maxColumns +col] = row*col end end -- Access the array for row=1,maxRows do for col=1,maxColumns do print(array[row*maxColumns +col]) end end
The output result of the above code is as follows:
1 2 3 2 4 6 3 6 9
As you can see, in the above examples, the array is set to a specified index value to avoid nil values, which is beneficial for saving memory space.