table||doc136772

September 20, 2022

table

Table is a data structure of lua, which is used to help us create different data types, such as arrays, dictionaries, etc.

Lua table uses an associative array. You can use any type of value to index the array, but the value cannot be nil.

Lua tables are not fixed in size. You can expand them according to your needs.

Lua also solves modules, packages, and objects through tables. For example, string Format means to use "format" to index table string.

Construction of table

Constructors are expressions that create and initialize tables. Tables are powerful things unique to Lua. The simplest constructor is {}, which is used to create an empty table. You can initialize the array directly:

--Initialization table

When we set the element for table a and assign a to B, both a and B point to the same memory. If a is set to nil, B can also access table elements. If no specified variable points to a, Lua's garbage collection mechanism will clean up the corresponding memory.

The following example demonstrates the above description:

example

–Simple table

mytable = {}

The execution result of the above code is:

The type of mytable is table

Table operation

The following lists the common methods of table operation:

Serial number Method & use
1 table.concat (table [, sep [, start [, end]]]):
2 table.insert (table, [pos,] value):
3 table.maxn (table)
4 table.remove (table [, pos])
5 table.sort (table [, comp])

Next, let's look at some examples of these methods.

Table connection

We can use concat() to output a string formed by connecting the elements in the list:

example

fruits = {"banana","orange","apple"}

Execute the above code and the output result is:

Connected string bananaorangeapple

Insert and remove

The following example demonstrates the insert and remove operations of a table:

example

fruits = {"banana","orange","apple"}

Execute the above code and the output result is:

The element with index 4 is mango

Table sort

The following example demonstrates the use of the sort () method to sort tables:

example

fruits = {"banana","orange","apple","grapes"}

Execute the above code and the output result is:

Before sorting

Table Max

table. Maxn this method no longer exists after lua5.2. We defined table_ Maxn method.

The following example demonstrates how to get the maximum value in a table:

example

function table_ maxn(t)

Execute the above code and the output result is:

TBL Max: 34

Note: when we get the length of a table, whether we use y or table Getn all of them will stop counting at the place where the index is interrupted, so that the length of the table cannot be obtained correctly. Instead, use the following method: function table_ leng(t) local leng=0 for k, v in pairs(t) do leng=leng+1 end return leng; end