lua-users home
lua-l archive

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

On Tue, Dec 08, 2009 at 06:44:16PM +0200, steve donovan wrote:
> As for table comparison, this is the one I use in Penlight:

I propose some changes (for efficiency and correctness). Three changed
lines are marked with --[[ ** ]] at previous line

And does this function the 'right thing' when userdata
(with metatable.__eq) are compared?

function deepcompare(t1,t2,ignore_mt)
    local ty1 = type(t1)
    local ty2 = type(t2)
    if ty1 ~= ty2 then return false end
    -- non-table types can be directly compared
--[[ ** ]]
    if ty1 ~= 'table' then return t1 == t2 end
    -- as well as tables which have the metamethod __eq
    local mt = getmetatable(t1)
    if not ignore_mt and mt and mt.__eq then return t1 == t2 end
    for k1,v1 in pairs(t1) do
        local v2 = t2[k1]
--[[ ** ]]
        if v2 == nil or not deepcompare(v1,v2, ignore_mt) then return false end
    for k2,v2 in pairs(t2) do
        local v1 = t1[k2]
--[[ ** ]]
	if v1 == nil then return false end
    return true

All best,