Lua的table库函数insert、remove、concat、sort详细介绍
函数列表:
table.insert(table,[pos,]value)
table.remove(table[,pos])
table.concat(table[,sep[,i[,j]]])
table.sort(table[,comp])
1.insert和remove只能用于数组元素的插入和移出,进行插入和移出时,会将后面的元素对齐起来。
所以在for循环中进行insert和remove的时候要注意插入和移除时是否漏掉了某些项:
localt={1,2,3,3,5,3,6} fori,vinipairs(t)do ifv==3then table.remove(t,i) end end --错误,第四个3没有被移除,ipairs内部会维护一个变量记录遍历的位置,remove掉第三个数字3之后,ipairs下一个返回的值是5而不是3 localt={1,2,3,3,5,3,6} fori=1,#tdo ift[i]==3then table.remove(t,i) i=i-1 end end --错误,i=i-1这段代码没有用,i的值始终是从1到#t,for循环里修改i的值不起作用 localt={1,2,3,3,5,3,6} fori=#t,1,-1do ift[i]==3then table.remove(t,i) end end --正确,从后往前遍历 localt={1,2,3,3,5,3,6} locali=1 whilet[i]do ift[i]==3then table.remove(t,i) else i=i+1 end end --正确,自己控制i的值是否增加
2.concat可以将table的数组部分拼接成一个字符串,中间用seq分隔。
lua中字符串的存储方式与C不一样,lua中的每个字符串都是单独的一个拷贝,拼接两个字符串会产生一个新的拷贝,如果拼接操作特别多,就会影响性能:
localbeginTime=os.clock() localstr="" fori=1,30000do str=str..i end localendTime=os.clock() print(endTime-beginTime) --消耗0.613秒,产生了30000个字符串拷贝,但只有最后一个是有用的
localbeginTime=os.clock() localt={} fori=1,30000do t[i]=i end localstr=table.concat(t,"") localendTime=os.clock() print(endTime-beginTime) --消耗0.024秒,利用concat,一次性把字符串拼接出来,只产生了一个字符串拷贝