Lua learning (11)--Lua array

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 multi-dimensional array.
The index key value of a Lua array can be represented by an integer, and the size of the array is not fixed.

one-dimensional array

One-dimensional arrays are the simplest arrays, and their logical structure is a linear table. One-dimensional arrays can be used to loop out the elements in the array, as follows:

array = {"Lua", "Tutorial"}

for i= 0, 2 do
   print(array[i])
end

The result is:

nil
Lua
Tutorial

**As you can see, we can use integer indexing to access array elements and return nil if the known index has no value.
In Lua index values ​​start at 1, but you can also specify 0 to start. **

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

Output result:

-4
-2
0
2
4

Multidimensional Arrays

A multi-dimensional array means that the index key of an array containing an array or a one-dimensional array corresponds to an array.
The following is a multidimensional array of arrays with three rows and three columns:

-- 初始化数组
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
end

The result is as follows:

1
2
3
2
4
6
3
6
9

A three-row three-column array multidimensional 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
end

Output result:

123246369

As you can see, in the above example, the array is set with the specified index value, which can avoid the occurrence of nil value, which is beneficial to save memory space.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325601317&siteId=291194637