Lua table 去重

原文: Lua table(表)

   wb070815

table 去重

function table.unique(t, bArray)
    local check = {}
    local n = {}
    local idx = 1
    for k, v in pairs(t) do
        if not check[v] then
            if bArray then
                n[idx] = v
                idx = idx + 1
            else
                n[k] = v
            end
            check[v] = true
        end
    end
    return n
end
更多解析

  Colin

-- table 去重
table = {1 , 2 , 3 , 4 , 20 , 6 , 7 , 7 , 15 , 28};
function table_unique(t) 
    local check = {};
    local n = {};
    for key , value in pairs(t) do
        if not check[value] then
            n[key] = value
            check[value] = value
        end
    end
    return n
end 

for key , value in pairs(table_unique(table)) do
    print('value is ' , value)
end

  wildwolf

table 泛型元素去重, 只要元素支持 == 比较。

要写成完全的泛型,那么 v==a[i] 改成一个比较函数的指针 equal(v,a[i]):

function removeRepeated(a)
    for k,v in pairs(a) do
        local count=0
        for j in pairs(a)do count=count+1 end
        for i=k+1,count do
            if v==a[i] then
                table.remove(a,i)
            end
        end
    end
end
local a={"a","d","c","g","d","w","c","a","g","s"}
removeRepeated(a)
for k,v in pairs(a) do
       print(k,v)
end

忘记密码?

如何获取邀请码?

关闭