這個庫提供了表處理的通用函數(shù)。 所有函數(shù)都放在表 table霉涨。
無論何時按价,若一個操作需要取表的長度, 這張表必須是一個真序列笙瑟。
table.concat(list, [, sep, [, i , [, j]]])
提供一個列表楼镐,其所有元素都是字符串或數(shù)字,返回字符串 list[i]..sep..list[i+1] ··· sep..list[j]逮走。 sep 的默認值是空串鸠蚪, i 的默認值是 1 今阳, j 的默認值是 #list 师溅。 如果 i 比 j 大茅信,返回空串。
sep為元素之間的間隔符
local testTab = {1,2,3,4,5,6,7}
print(table.concat(testTab))
print (table.concat(testTab, "*", 1,3))
Output:
1234567
1*2*3
table.insert(table, [pos,] , value)
在 list 的位置 pos 處插入元素 value 墓臭, 并后移元素 list[pos], list[pos+1], ···, list[#list] 蘸鲸。 pos 的默認值為 #list+1 , 因此調用 table.insert(t,x) 會將 x 插在列表 t 的末尾窿锉。
function printTable(tab)
local output = ""
for i,v in ipairs(tab) do
output = output..v.." "
end
print(output)
end
local testTab = {1,2,3,4}
table.insert(testTab, 5)
printTable(testTab)
table.insert(testTab,2,10)
printTable(testTab)
table.insert(testTab, 8, 1)
printTable(testTab)
Output:
1 2 3 4 5
1 10 2 3 4 5
1 10 2 3 4 5
table.maxn(table)
函數(shù)返回指定table中所有正數(shù)key值中最大的key值. 如果不存在key值為正數(shù)的元素, 則返回0酌摇。 此函數(shù)不限于table的數(shù)組部分
local tab = {1,2,3,4}
tab[100] = 2
print(table.maxn(tab))
tab[192.1] = 10
print(table.maxn(tab))
print(#tab)
Output:
100
192.1
4
** lua 5.3中被移除 **
table.remove(table [, pos])
移除 list 中 pos 位置上的元素,并返回這個被移除的值嗡载。 當 pos 是在 1 到 #list 之間的整數(shù)時窑多, 它向前移動元素 list[pos+1], list[pos+2], ···, list[#list] 并刪除元素 list[#list]; 索引 pos 可以是 #list + 1 洼滚,或在#list 為 0 時可以是 0 埂息; 在這些情況下,函數(shù)刪除元素 list[pos]遥巴。
pos 默認為 #list千康, 因此調用 table.remove(l) 將移除表 l 的最后一個元素。
function printTable(tab)
local output = ""
for i,v in ipairs(tab) do
output = output..v.." "
end
print(output)
end
local tab = {1,2,3,4,5,6,7}
print(table.remove(tab))
printTable(tab)
print(table.remove(tab,2))
printTable(tab)
Output:
7
1 2 3 4 5 6
2
1 3 4 5 6
table.sort(table, [, comp])
在表內從 list[1] 到 list[#list] 原地 對其間元素按指定次序排序铲掐。 如果提供了 comp 拾弃, 它必須是一個可以接收兩個列表內元素為參數(shù)的函數(shù)。 當?shù)谝粋€元素需要排在第二個元素之前時摆霉,返回真 (因此 not comp(list[i+1],list[i]) 在排序結束后將為真)豪椿。 如果沒有提供 comp, 將使用標準 Lua 操作 < 作為替代品携栋。
排序算法并不穩(wěn)定搭盾; 即當兩個元素次序相等時,它們在排序后的相對位置可能會改變刻两。
function printTable(tab)
local output = ""
for i,v in ipairs(tab) do
output = output..v.." "
end
print(output)
end
local tab = {1,6,7,4,3,9}
table.sort(tab)
printTable(tab)
table.sort(tab, function(a,b) return a > b end)
printTable(tab)
Output:
1 3 4 6 7 9
9 7 6 4 3 1