推薦閱讀:
方法一
用過lua的人都知道,lua的table中不允許存在相同的key,利用這個思想,我們可以將原始table(記作table1),用一個新的table(記作table2)來存放,存放得時候將table1的value作為table2得key,將值賦為true,最后只需要遍歷table2,將其的key保存在一個新的table(記作table3)里。
例如:原始table1={1,2,3,4,5,2,3}
local table1={1,2,3,4,5,2,3}
local table2={}
for key,val in pairs(table1) do
table2[val]=true
end
local table3={}
for key,val in pairs(table2) do
table.insert(table3,key)--將key插入到新的table,構成最終的結果
end
方法二
local list={1,2,3,4,5,2,3}
local temp1 = clone(list)
local temp2 = clone(list)
for k1, v1 in ipairs(temp1) do
for k2, v2 in ipairs(temp2) do
if v1 == v2then
table.remove(temp1, k1)
table.remove(temp2, k1)
end
end
end
拓展:移除table中數據里具有某個相同字段的數據,例如,table如下:需移除具有相同value相同的數據
local list={}
list[1]={id=10001,sid=1001,value=5}
list[2]={id=10002,sid=1001,value=3}
list[3]={id=10003,sid=1001,value=4}
list[4]={id=10004,sid=1001,value=5}
利用方法二拓展本功能:
local list={}
list[1]={id=10001,sid=1001,value=5}
list[2]={id=10002,sid=1001,value=3}
list[3]={id=10003,sid=1001,value=4}
list[4]={id=10004,sid=1001,value=5}
local temp1 = clone(list)
local temp2 = clone(list)
for k1, v1 in ipairs(temp1) do
for k2, v2 in ipairs(temp2) do
--同種英雄同一星級的移除
if v1.id ~= v2.id and v1.value == v2.value and v1.sid == v2.sid then
table.remove(temp1, k1)
table.remove(temp2, k1)
end
end
end