Measure the test taker's knowledge about the array concept in Lua.
This article mainly introduces the concept of array in Lua, which is the foundation of Lua's entry-level learning. For more information, see
An array is a device for ordered objects. It can be a single two-dimensional array containing rows and columns or a collection of multi-dimensional arrays.
In Lua, arrays are implemented using index tables and integers. The size of the array is not fixed, and it can grow based on the memory limit we need.
One-dimensional array
A one-dimensional array can be represented by a simple table structure, initialized, and read through a simple for loop. The following is an example.
The Code is as follows:
Array = {"Lua", "Tutorial "}
For I = 0, 2 do
Print (array [I])
End
After running the above Code, we will get the following output.
The Code is as follows:
Nil
Lua
Tutorial
As shown in the code above, nil is returned when we try to access elements in an array that does not exist in the index. The Lua index usually starts with index 1, but it may be in index 0 and less than 0, as well as create objects. It is shown that we initialize the for loop Array Using the negative index array.
The Code is as follows:
Array = {}
For I =-2, 2 do
Array [I] = I * 2
End
For I =-2, 2 do
Print (array [I])
End
After running the above Code, we will get the following output.
The Code is as follows:
-4
-2
0
2
4
Multi-dimensional array
Multi-dimensional arrays can be implemented in two ways.
Array
One-dimensional arrays control indexes
For a 3, 3 multi-dimensional array, the following example shows how to use an array.
The Code is 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
After running the above Code, we will get the following output.
The Code is as follows:
1
2
3
2
4
6
3
6
9
The following example shows how to use an operation index for a 3, 3 multi-dimensional array.
The Code is 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
After running the above Code, we will get the following output.
The Code is as follows:
1
2
3
2
4
6
3
6
9
As shown in the preceding example, data is stored Based on indexes. You can also use sparse elements as a matrix to implement lua. Because it is not stored in the Lua zero value, it can save a lot of memory. In Lua, any special technology is used compared to other programming languages.