lua标准库之table库
table库的概念
是由一些操作table的辅助函数组成
作用一:对lua中的表的大小给出一个合理的解释,如getn,#table等
作用二:提供一些插入删除元素以及元素排序的函数,如insert,remove等
Lua5.1中字符串库的所有函数如下表:先定义一张表 t = {1,2,3}
函数 | 描述 | 示例 | 结果 |
---|---|---|---|
# | 取表长 | #t | 3 |
getn | 取表长 | Table.getn(t) | 3 |
setn | 设置table中的元素个数 | Table.setn(t,4) | 4 |
maxn | 返回表中最大key | Table.maxn(t) | 3 |
concat | 表连接 | ||
insert | 往表的指定位置插入key | table.insert(t,4) | {1,2,3,4} |
remove | 删除表的指定位 | table.remove(table,3) | {1,2,3} |
sort | 给表排序,默认升序 | table.sort(t) | {1,2,3} |
取表长
两种方法#和getn
#:返回表的长度(只返回变量是数字的和当nil在非最后一个元素的位置)
table.getn(t):返回表中元素的个数(只返回变量是数字的) 在lua5.3中已不可使用1
2
3local t = {1,2,3,4,5,6,7,}
print(#t) -- 7
print(table.getn(t)) -- 7
table.insert
往指定表插入一个元素,有不带参数和带参数两种方法
不带参数:插入位置就是最后一个位置
1 | local t ={1,2,3} |
带参数,可以指定插入到第几个位置
1 | local t = {1,2,3} |
table.remove
从指定列表删除一个元素
不带参数:默认删除最后一个参数
1 | local t = {1,2,3} |
带参数:可以指定删除某个位置
1 | local t = {1,2,3} |
table.sort
table.sort(表名,排序函数)
对指定表进行排序操作,有不带排序函数和带排序函数两种
不带排序函数:默认升序,从小到大
带排序函数:自定义函数
1 | local s = "" |
1 | a = {"banana","orange","apple","grapes"} |
table.concat
table.concat(表名,分隔符)
连接表中的元素,那么输出的是字符串类型
第一个参数为要连接的表
第二个参数为连接时使用的分隔符
有第二个参数不写和写两种的方法
分隔符不写:直接连接,输出结果为字符串1
2
3
4local s = ""
local t = {1,4,7,3,11,9,8}
print(type(table.concat(t))) -- string
print(table.concat(t)) -- 14731198
有分隔符1
2
3
4
5
6local s = ""
local t = {1,4,7,3,11,9,8}
print(type(table.concat(t,""))) -- string
print(table.concat(t,".")) -- 1.4.7.3.11.9.8
print(table.concat(t,"\t")) -- 1 4 7 3 11 9 8
print(table.concat(t,"~-~")) -- 1 ~-~4 ~-~7 ~-~3 ~-~11 ~-~9 ~-~8
table的结构
构造器是创建和初始化表的表达式
表是lua特有的功能强大的东西。最简单的构造函数是{},用来创建一个空表,可以直接初始化数组1
2
3
4
5
6
7
8-- 初始化表
mytable = {}
--指定值
mytable[1] = "lua"
-- 移除引用
mytable = nil
lua垃圾回收会释放内存
当我们为table a 并设置元素,然后a复制给b,则a与b都指向同一个内存
如果a设置为nil,则b同样能访问table元素
如果没有指定的变量指向,lua的垃圾回收机制会清理对应的内存1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18--[简单的table]
mytable = {}
print("mytable 的类型是",type(mytable)) --mytable的类型是table
mytable[1] = "Lua"
mytable["wow"] = "修改前"
print("mytable索引为1的元素是:",mytable[1]) --mytable索引为1的元素是:Lua
print("mytable索引为wow的元素是:",mytable["wow"]) --mytable索引为wow的元素是:修改前
-- [alternatetable 和 mytable 的是指向同一个table]
alternatetable = mytable
print("alternatetable索引为wow的元素是:",alternatetable["wow"]) --alternatetable索引为wow的元素是:修改前
alternatetable["wow"] = "修改后"
print("mytable索引为wow的元素是:",mytable["wow"]) -- mytable索引为wow的元素是: 修改后
-- [释放变量]
alternatetable = nil
print("alternatetable 是:",alternatetable) --alternatetable 是:nil
print("mytable索引为wow的元素是:",mytable["wow"]) -- mytable索引为wow的元素是:修改后
mytable = nil
print("mytable 是:",mytable) --mytable 是:nil
判断table是否是空表
可以用next函数来判断空表,next(table,[,index])第一个参数是表,第二个参数是标的索引值。返回索引和对应的值,当不传入index,默认index为表的首位索引1
2
3
4local t = {}
if nil ~= t and "table" == type(t) then
print(next(t)) -- nil
end
1 | local t = {10} |
注意:next如果传入的参数不是tbale或者为nil,脚本会报错,所以上面要加上这个两个判断