Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table diff key function

Tags:

lua

How could I check if a table (as array) contains all the keys of another table? Something like array_diff_key in PHP: https://www.php.net/manual/en/function.array-diff-key.php

This function should return, for example, ["firstLevel"]["e"] because this element doesn't exist in tblTwo:

tblOne = {
    ["firstLevel"] = {
        ["a"] = "something",
        ["b"] = "something",
        ["c"] = "something",
        ["subLevel"] = {
            ["d"] = "something",
            ["e"] = "something",
        }
    }

tblTwo = {
    ["firstLevel"] = {
        ["a"] = "something",
        ["b"] = "something",
        ["c"] = "something",
        ["subLevel"] = {
            ["d"] = "something",
        }
    }
like image 675
Zax Avatar asked Jul 03 '26 23:07

Zax


1 Answers

Try the code below:

function diff(a,b,s)
    for k,v in pairs(a) do
        if b[k]==nil then return s.."."..k end
        if type(v)=="table" then
            local w=diff(v,b[k],k)
            if w~=nil then return s.."."..w end
        end
    end
end

print(diff(tblOne,tblTwo,"TOP"))
like image 187
lhf Avatar answered Jul 05 '26 14:07

lhf