An array is an ordered arrangement of objects, which can be a one-dimensional array containing a collection of rows, or a multidimensional array containing multiple rows and columns.
In Lua, arrays are implemented using indexed tables with integers. The size of the array is not fixed and can grow as required by the tutorial (depending on memory constraints).
one-dimensional array
One-dimensional arrays can be represented using a simple table structure, and can be initialized and read using a simple for loop. One is shown below.
array = { "Lua", "Tutorial"} for i = 0, 2 do print(array[i]) end
When the above code is run, the following output will be obtained.
nil Lua Tutorial
As you can see in the code above, when trying to access an element at an index that doesn't exist in the array, it returns nil. In Lua, indexing usually starts at index 1. But objects can also be created at index 0 and below. An array using negative indices is shown below, where a for loop is used to initialize the array.
array = {} for i= -2, 2 do array[i] = i *2 end for i = -2,2 do print(array[i]) end
When the above code is run, the following output will be obtained.
-4 -2 0 2 4
Multidimensional Arrays
The following shows an example of a multidimensional array of 3.3 using an array of arrays.
-- Initializing the array array = {} for i=1,3 do array[i] = {} for j=1,3 do array[i][j] = i*j end end -- Accessing the array for i=1,3 do for j=1,3 do print(array[i][j]) end end
When the above code is run, the following output will be obtained.
1 2 3 2 4 6 3 6 9
An example of a multidimensional array using manipulated indices is shown below.
-- Initializing 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 -- Accessing the array for row=1,maxRows do for col=1,maxColumns do print(array[row*maxColumns +col]) end end
When Wu Ya Tutorial runs the above code, the following output will be obtained.
1 2 3 2 4 6 3 6 9