Lua table(table)


table is a data structure in Lua that helps us create different data types, such as numbers, dictionaries, etc.

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

Lua table has no fixed size and you can expand it according to your needs.

Lua also uses tables to solve modules, packages and objects. For example, string.format means using "format" to index table string.


Construction of table (table)

The constructor is an expression that creates and initializes the table. Tables are a powerful thing unique to Lua. The simplest constructor is {}, which creates an empty table. You can initialize the array directly:

-- 初始化表
mytable = {}

-- 指定值
mytable[1]= "Lua"

-- 移除引用
mytable = nil
-- lua 垃圾回收会释放内存

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

The following example demonstrates the above description:

-- 简单的 table
mytable = {}
print("mytable 的类型是 ",type(mytable))

mytable[1]= "Lua"
mytable["wow"] = "修改前"
print("mytable 索引为 1 的元素是 ", mytable[1])
print("mytable 索引为 wow 的元素是 ", mytable["wow"])

-- alternatetable和mytable的是指同一个 table
alternatetable = mytable

print("alternatetable 索引为 1 的元素是 ", alternatetable[1])
print("mytable 索引为 wow 的元素是 ", alternatetable["wow"])

alternatetable["wow"] = "修改后"

print("mytable 索引为 wow 的元素是 ", mytable["wow"])

-- 释放变量
alternatetable = nil
print("alternatetable 是 ", alternatetable)

-- mytable 仍然可以访问
print("mytable 索引为 wow 的元素是 ", mytable["wow"])

mytable = nil
print("mytable 是 ", mytable)

The execution result of the above code is:

mytable 的类型是 	table
mytable 索引为 1 的元素是 	Lua
mytable 索引为 wow 的元素是 	修改前
alternatetable 索引为 1 的元素是 	Lua
mytable 索引为 wow 的元素是 	修改前
mytable 索引为 wow 的元素是 	修改后
alternatetable 是 	nil
mytable 索引为 wow 的元素是 	修改后
mytable 是 	nil

Table operation

is listed below Commonly used methods for Table operations:

Serial numberMethod & Purpose
1 table.concat (table [, sep [, start [, end]]]):

concat is the abbreviation of concatenate (chain, connection). The table.concat() function lists the parameters specified in All elements in the array part of the table from the start position to the end position are separated by the specified separator (sep).

2table.insert (table, [pos,] value):

Specified in the array part of table Insert an element with value at position (pos). The pos parameter is optional and defaults to the end of the array part.

3table. maxn (table)

Specifies the largest key value among all positive key values ​​in the table. If there is no element with a positive key value, 0 is returned. (This method no longer exists after Lua5.2, this article uses a custom function to implement)

4table.remove (table [, pos])

Returns the element at the pos position in the table array part. The subsequent elements will be moved forward. The pos parameter is optional, and the default is the length of the table, that is, starting from the last Element is deleted.

5table.sort (table [, comp])

Sort the given table in ascending order.

Next let’s look at examples of these methods.

Table connection

We can use the concat() method to connect two tables:

fruits = {"banana","orange","apple"}
-- 返回 table 连接后的字符串
print("连接后的字符串 ",table.concat(fruits))

-- 指定连接字符
print("连接后的字符串 ",table.concat(fruits,", "))

-- 指定索引来连接 table
print("连接后的字符串 ",table.concat(fruits,", ", 2,3))

The output result of executing the above code is:

连接后的字符串 	bananaorangeapple
连接后的字符串 	banana, orange, apple
连接后的字符串 	orange, apple

Insert and Remove

The following example demonstrates the insertion and removal operations of table:

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

-- 在末尾插入
table.insert(fruits,"mango")
print("索引为 4 的元素为 ",fruits[4])

-- 在索引为 2 的键处插入
table.insert(fruits,2,"grapes")
print("索引为 2 的元素为 ",fruits[2])

print("最后一个元素为 ",fruits[5])
table.remove(fruits)
print("移除后最后一个元素为 ",fruits[5])

The output result of executing the above code is:

索引为 4 的元素为 	mango
索引为 2 的元素为 	grapes
最后一个元素为 	mango
移除后最后一个元素为 	nil

Table sorting

The following The example demonstrates the use of the sort() method for sorting Table:

fruits = {"banana","orange","apple","grapes"}
print("排序前")
for k,v in ipairs(fruits) do
	print(k,v)
end

table.sort(fruits)
print("排序后")
for k,v in ipairs(fruits) do
	print(k,v)
end

The output result of executing the above code is:

排序前
1	banana
2	orange
3	apple
4	grapes
排序后
1	apple
2	banana
3	grapes
4	orange

Table maximum value

table.maxn This method no longer exists after Lua5.2, and we define the table_maxn method to implement it.

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

function table_maxn(t)
    local mn = 0
    for k, v in pairs(t) do
        if mn < k then
            mn = k
        end
    end
    return mn
end
tbl = {[1] = "a", [2] = "b", [3] = "c", [26] = "z"}
print("tbl 长度 ", #tbl)
print("tbl 最大值 ", table_maxn(tbl))

The output result of executing the above code is:

tbl 长度 	3
tbl 最大值 	26