lua-users home
lua-l archive

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

> 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
>    Enrico

I assume your question to be restricted to "pure Lua"
scripting. So a 'crazy Moe' version could be:

function compareTables(t1, t2)
        return (#a == #b) and (unpack(t1) == unpack(t2))

I love understandable and short 'Crazy Moe' solutions.
Though, we all know 'common sense' ~= testing and benchmarks...
Replacing the unpack with your first loop makes exactly
the same you intended to do in a cleaner and faster
way however. 

IMHO the following is a more rational solution 
[...] in the same unpack(TM) fashion. Perhaps surprisingly
faster as this one exits quickly on limit cases 
(but I myself consider this 'if' usage very inelegant)

function compareTables(t1, t2)
	if a == b then
		return true
	elseif #a == #b then
		return unpack(t1) == unpack(t2)
		return false

Once again, this is untested and you aren't talking
to an expert :p


Mario García H.