Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find difference between two arrays in Lua

Tags:

loops

lua

Let's say I have two arrays

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

How can I compare the two arrays, and detect the entries in array b which aren't in array a?

like image 976
Ryan Butterworth Avatar asked Oct 19 '25 17:10

Ryan Butterworth


2 Answers

Try this code:

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

If a does not change, you need to build A only once.

All this would be easier if you used sets instead of lists. The first loop builds the set of values in the list a.

Or you can write them as sets in the first place:

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

With sets, you don't need any loops: if k contains a string you want to test, then a has k iff a[k]==true.

like image 66
lhf Avatar answered Oct 22 '25 00:10

lhf


That's how I do it: for each key (oops, meant value) in table b, I check if each doesn't exist in table a, just like a filter.

-- 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);

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!