Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Lua array


May 12, 2021 Lua


Table of contents


Lua array

An array, a collection of elements of the same data type in a certain order, can be a one-dimensional array and a multi-dimensional array.

The index key value of the Lua array can be represented by an integer, and the size of the array is not fixed.


A one-dimensional array

A one-dimensional array is the simplest array, and its logical structure is a linear table. A one-dimensional array can be used to loop out elements in an array, as follows:

array = {"Lua", "Tutorial"}

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

The above code executes the output as follows:

nil
Lua
Tutorial

As you can see, we can use an integer index to access array elements and return nil if we know that the index has no value.

The lua index value starts with 1, but you can also specify 0 to start with.

In addition, we can index values with negative numbers as arrays:

array = {}

for i= -2, 2 do
   array[i] = i *2
end

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

The above code executes the output as follows:

-4
-2
0
2
4

Multi-dimensional array

A multi-dimensional array is an array that contains an array or an index key for a one-dimensional array.

Here is a three-row, three-column array of multi-dimensional arrays:

-- 初始化数组
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 above code executes the output as follows:

1
2
3
2
4
6
3
6
9

Three rows of three-column array arrays 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

The above code executes the output as follows:

1
2
3
2
4
6
3
6
9

As you can see, in the example above, the array sets the specified index value, which avoids the nil value and helps save memory space.