Friday, December 19, 2008

Lua Deep Equals

I was surprised when I couldn't easily google for a Lua deep compare function. It's main purpose is to compare tables and check if they have the same values, but of course it's recursive so it just uses ~= to check for difference in non-tables.

Anyway, so I wrote my own and figured I'd post it here for posterity. Maybe you can come up with a shorter version?

-- Deep Equals
local function equals(t1, t2)
   if t1 == t2 then
       return true
   end
   if type(t1) ~= "table" or type(t2) ~= "table" then
       return false
   end
   local v2
   for k,v1 in pairs(t1) do
       v2 = t2[k]
       if v1 ~= v2 and not equals(v1, t2[k]) then
           return false
       end
   end
   for k in pairs(t2) do
       if t1[k] == nil then
           return false
       end
   end
   return true
end