lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Dec 27, 2008 at 2:46 PM, Enrico Colombini <erix@erix.it> wrote:
> Is there a better/simpler way to do a shallow table compare (meaning that
> the two tables must have the same keys with identical values)?

> function compareTables(t1, t2)
>    -- all key-value pairs in t1 must be in t2
>    for k, v in pairs(t1) do
>        if t2[k] ~= v then return false end
>    end
>    -- there must not be other keys in t2
>    for k, v in pairs(t2) do
>        if t1[k] == nil then return false end
>    end
>    return true
> end

If you can afford to corrupt one of the tables, you can optimize out
second loop (untested code):

function compareTables(t1, t2)
   -- all key-value pairs in t1 must be in t2
   for k, v in pairs(t1) do
       if t2[k] ~= v then return false end
       t2[k] = nil
   end
   return next(t2) == nil -- there must not be other keys in t2
end

Alexander.