友情提示:自己学习总结,不喜勿喷。
感谢并推荐:http://www.runoob.com/ 菜鸟教程
注意:以下代码,建议自己敲一遍,因为没有写上输出结果。自己敲过,试过,更容易理解。
1..table.insert
--触类旁通--向table内添加数据
table1 = {"Iverson", 32, "SG"}
table2 = {"Irving", 26, "PG"}
table3 = {"James", 28, "PF"}
table4 = {"Jordon", 38, "SF"}
team1 = {}
team2 = {}
table.insert(team1, table1)
table.insert(team1, table2)
table.insert(team1, table3)
table.insert(team1, table4)
for k, v in ipairs(team1) do
local curtb = {}
curtb.name = v[1]
curtb.age = v[2]
curtb.title = v[3]
table.insert(team2, curtb)
end
for k, v in pairs(team2) do
for j, l in pairs(v) do
print(j.." : "..l)
end
end
================================================
2..table.remove
-- 移除方法1:
local bullet = { 'a','b','b','d','e','a','f','g','h','i','b','k','l','a','n','o','b' }
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 newv = z
local newT = {}
for i ,v in ipairs(bullet) do
if newv ~= v and "a" ~= v then --可作为同时移除多个元素
table.insert(newT , v) --存放到临时表中,这里只存放原表的引用
end
end
bullet = newT -- 将原表指向临时表,实现移除
for k, v in ipairs(bullet) do
print(k, v)
end
====================
-- 移除方法2:
--通过创建临时标记表remove,来标记准备删除的元素
local removes = { a = true, b = true, c = true, e = true, f = true, p = true }
local i = 1
while i <= #bullet do
if removes[bullet[i]] then
table.remove(bullet,i);
else
i = i + 1;
end
end
===============================================
4..排序
local tables = {9,5,8,3,1,5,7}
table.sort(tables)--整理排序
for i in ipairs(tables) do
print(tables[i])
end
======================================
--键值排序:参与排序的是键
local test1 ={a=1,f=9,d=2,c=8,b=5}
local keyTest={}
for i in pairs(test1) do
print("=="..i)
table.insert(keyTest, i)
end
table.sort(keyTest)
for i,v in ipairs(keyTest) do
print(v,test1[v])
end
=====================================================
--触类旁通--表单排序
local test2 =
{
{id=1, name="deng"},
{id=9, name="luo"},
{id=2, name="yang"},
{id=8, name="ma"},
{id=5, name="wu"},
}
table.sort(test2,
function(a, b)
return a.id < b.id
end
)
for i in pairs(test2) do
print(test2[i].id.."=="..test2[i].name)
end
============================================