How to check if two tables(objects) have the same value in Lua

后端 未结 6 1604
粉色の甜心
粉色の甜心 2021-01-04 02:00

I wanna check if two tables have the same value in Lua, but didn\'t find the way.

I use the operator ==, it seems just to check the same objects, but no

6条回答
  •  天涯浪人
    2021-01-04 02:50

    I currently use this

    local tableCompare
    do
        local compare
        compare = function(src, tmp, _reverse)
            if (type(src) ~= "table" or type(tmp) ~= "table") then
                return src == tmp
            end
    
            for k, v in next, src do
                if type(v) == "table" then
                    if type(tmp[k]) ~= "table" or not compare(v, tmp[k]) then
                        return false
                    end
                else
                    if tmp[k] ~= v then
                        return false
                    end
                end
            end
            return _reverse and true or compare(tmp, src, true)
        end
        tableCompare = function(src, tmp, checkMeta)
            return compare(src, tmp) and (not checkMeta or compare(getmetatable(src), getmetatable(tmp)))
        end
    end
    
    print(tableCompare({ 1 , b = 30 }, { b = 30, 1 }, false))
    

提交回复
热议问题