LuaTable函数库

1.5k 词
1
2
3
4
5
6
7
table.insert(table,[ pos,] value) 
table.remove(table[, pos])
table.concat(table[, sep[, i[, j]]])
table.sort(table[, comp]) // 见Lua排序

table.getn() //5.0
table.maxn() //5.2

#####insert, remove

insert 和 remove 只能用于数组元素的插入和移出, 进行插入和移出时,会将后面的元素对齐起来。
所以在 for 循环中进行 insert 和 remove 的时候要注意插入和移除时是否漏掉了某些项:
local t = {1,2,3,3,5,3,6}
for i,v in ipairs(t) do
if v == 3 then
table.remove(t,i)
end
end
– 错误,第四个 3 没有被移除,ipairs 内部会维护一个变量记录遍历的位置,remove 掉第三个数字 3 之后,ipairs 下一个返回的值是 5 而不是 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
local t = {1,2,3,3,5,3,6} 
for i=1, #t do
if t[i] == 3 then
table.remove(t,i)
i = i-1
end
end


local t = {1,2,3,3,5,3,6}
for i=#t, 1, -1 do
if t[i] == 3 then
table.remove(t,i)
end
end
-- 正确,从后往前遍历

local t = {1,2,3,3,5,3,6}
local i = 1
while t[i] do
if t[i] == 3 then
table.remove(t,i)
else
i = i+1
end
end
-- 正确,自己控制 i 的值是否增加
Concat

concat 可以将 table 的数组部分拼接成一个字符串,中间用 seq 分隔。
lua 中字符串的存储方式与 C 不一样,lua 中的每个字符串都是单独的一个拷贝,拼接两个字符串会产生一个新的拷贝,如果拼接操作特别多,就会影响性能:
local beginTime = os.clock()
local str = “”
for i=1, 30000 do
str = str .. i
end
local endTime = os.clock()
print(endTime - beginTime)
– 消耗 0.613 秒,产生了 30000 个字符串拷贝,但只有最后一个是有用的

​ local beginTime = os.clock()
​ local t = {}
​ for i=1, 30000 do
​ t[i] = i
​ end
​ local str = table.concat(t, “”)
​ local endTime = os.clock()
​ print(endTime - beginTime)
​ – 消耗 0.024 秒,利用 concat,一次性把字符串拼接出来,只产生了一个字符串拷贝

maxn
  • 原型:table.maxn (tab_table)
  • 解释:返回一个表tab_table中的最大正数索引,如果没有正数索引的话返回0。
  • 总结#
    • 这个函数比较简单,行为和函数解释一致,不要求索引必须连续,返回一个最大的正数索引
    • 有运行结果可知,当表中只有非数字索引或者负数索引时,函数返回0。
    • 其中官方文档中有一句话,大意是说这个函数的工作原理就是线性的遍历了这个表

https://www.cnblogs.com/whiteyun/archive/2009/08/10/1543139.html

https://www.cnblogs.com/slysky/p/5360387.html