An array is the device of an ordered object, which can be a single two-dimensional array of rows or multidimensional arrays containing multiple rows and columns.
In Lua, arrays are implemented using index tables and integers. The size of the array is not fixed, and it can grow based on what we need to be restricted by the memory.
one-dimensional arrays
A one-dimensional array can be represented by a simple table structure that can be initialized and read using a simple for loop. Shown in the following example.
Copy Code code as follows:
Array = {"Lua", "Tutorial"}
For i= 0, 2 do
Print (Array[i])
End
When we run the above code, we get the following output.
Copy Code code as follows:
As you can see in the code above, when we try to access an element in an array that does not exist in the index, we return nil. The LUA index usually starts at index 1, but it is possible to index 0 and less than 0, and to create objects. Display using a negative index array we initialize using a For loop array.
Copy Code code as follows:
Array = {}
For i=-2, 2 do
Array[i] = i *2
End
For i = -2,2 do
Print (Array[i])
End
When we run the above code, we get the following output.
Copy Code code as follows:
Multidimensional arrays
Multidimensional arrays can be implemented in two ways.
- An array of arrays
- One-dimensional arrays are indexed by control
For a 3, 3-dimensional array, an example of an array using arrays is shown below.
Copy Code code as follows:
--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 we run the above code, we get the following output.
Copy Code code as follows:
For a 3, 3-dimensional array example, use the operation index as shown below.
Copy Code code as follows:
--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 we run the above code, we get the following output.
Copy Code code as follows:
As you can see in the example above, the data is stored based on the index. It is also possible to put elements in a sparse way, and it is a matrix that works in LUA implementations. Because it does not preserve the LUA 0 value, it can save a lot of memory and use special techniques in any particular technology in LUA compared to other programming languages.