在Lua中比较两个数组

时间:2016-12-10 17:07:39

标签: loops lua

假设我有两个数组

a = { "apple", "pear", "orange", "pineapple", "tomato" }
b = { "kiwi", "strawberry", "melon" }

如何比较两个数组,并检测数组b中不在数组a中的条目?

2 个答案:

答案 0 :(得分:1)

试试这段代码:

A = {}
for k,v in pairs(a) do
        A[v]=true
end

for k,v in pairs(b) do
        if A[v]==nil then print(v,"not in a") end
end

如果a没有变化,则只需构建一次A

如果您使用 sets 而不是 lists ,这一切都会更容易。第一个循环在列表a中构建一组值。

或者您可以先将它们作为集合编写:

a = { ["apple"]=true, ["pear"]=true, ["orange"]=true, ["pineapple"]=true, ["tomato"]=true }   
b = { ["kiwi"]=true, ["strawberry"]=true, ["melon"]=true}

使用集合,您不需要任何循环:如果k包含您要测试的字符串,则ak iff a[k]==true

答案 1 :(得分:0)

我就是这样做的:对于表b中的每个(oops,意思是值),我检查表a中是否每个都不存在,只是像过滤器一样。

-- Filter table #1.
-- @return A table.
function table:filter(filterFnc)
    local result = {};

    for k, v in ipairs(self) do
        if filterFnc(v, k, self) then
            table.insert(result, v);
        end
    end

    return result;
end

-- Get index of a value at a table.
-- @param any value
-- @return any
function table:find(value)
    for k, v in ipairs(self) do
        if v == value then
            return k;
        end
    end
end

a = { "apple", "pear", "orange", "pineapple", "tomato" };
b = { "kiwi", "strawberry", "melon" };

local additions;

-- filter b to check additions
additions = table.filter(b, function(value)
    return not table.find(a, value);
end);