Lua 中 table 库函数 insert、remove、sort
一、 insert 插入
do
--> table.insert 插入函数
tab = {"a", "c", "d", "b"}
-- 在 tab 末尾添加 元素 "e"
table.insert(tab, "e")
-- 在 tab 末尾添加 元素 "f"
print(table.insert(tab, "f"))
-- 输出结果: 无输出,即 table.insert 函数无返回值
-- 在 tab 第 2 个元素后 添加 "g"
table.insert(tab, 2, "g")
for i,v in ipairs(tab) do
print(i,v)
end
-- 输出结果:
-- 1 a
-- 2 g
-- 3 c
-- 4 d
-- 5 b
-- 6 e
-- 7 f
end
二、 remove 移除
do
--默认移除表中最后一个元素
--table.remove(t)
-- 移除表中第 index 个元素
-- table.remove(t, index)
t = {"a", "b", "c", "d"}
-- 默认移除 最后一个元素
table.remove(t)
-- 移除 表 t 中 第 1 个元素
table.remove(t, 1)
for k,v in pairs(t) do
print(k,v)
end
-- 输出结果:
-- 1 b
-- 2 c
end
三、sort 排序
do
tab = {"d", "b", "a", "c"}
-- 默认按照升序对 表 tab 进行排序
table.sort( tab )
for i,v in ipairs(tab) do
print(i,v)
end
-- 输出结果:
-- 1 a
-- 2 b
-- 3 c
-- 4 d
tab2 = {"d", "b", "a", "c"}
-- 定义一个降序排序的函数
function sortfunction( a, b )
return a > b
end
-- 将 tab2 按照 sortfunction 函数进行排序
-- tab2 会按照降序进行排序
table.sort( tab2, sortfunction )
for i,v in ipairs(tab2) do
print(i,v)
end
--输出结果:
-- 1 d
-- 2 c
-- 3 b
-- 4 a
end