1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| local function table_equals(t1, t2, seen) seen = seen or {} if t1 == t2 then return true end if type(t1) ~= "table" or type(t2) ~= "table" then return false end if seen[t1] then return seen[t1] == t2 end seen[t1] = t2 local count1, count2 = 0, 0 for k in pairs(t1) do count1 = count1 + 1 if t2[k] == nil and not table_equals(nil, t2[k]) then return false end end for k in pairs(t2) do count2 = count2 + 1 end if count1 ~= count2 then return false end for k, v in pairs(t1) do if not table_equals(v, t2[k], seen) then return false end end return true end
local a = {1, 2, {3, 4}} local b = {1, 2, {3, 4}} local c = {1, 2, {3, 5}}
print(table_equals(a, b)) print(table_equals(a, c))
|