## comparing numeric tables

Alaran
Posts: 27
Joined: Sat Dec 19, 2009 2:51 pm

### comparing numeric tables

So.. basically I want to do this:

A function that takes 2 or more tables and "subtracts" table 2+ from table 1. So the return value would be a table with only those values that are unique to table 1.

The easiest way I can think of would be to loop through table 1 and add all those values to my return value that cannot be found in the other tables. But how do I make it so it accepts a varying amount of tables? Is there a way to do that?

ixokai
Posts: 63
Joined: Fri Dec 25, 2009 7:43 am

### Re: comparing numeric tables

You aren't "comparing" tables in any traditional sense, and I don't quite get where "numeric" comes into play-- from my understanding of your question, your tables are actually sets, and you want a set difference.

Lua doesn't support set operations directly, so I'd do:

Code: Select all

``````function difference(primary, ...)
-- first, let us make a copy of the main table: this may or may not be needed.
local result = {}
for k, v in pairs(primary) do
result[k] = v
end

- now, to get rid of everything in the other tables!
for _, tbl in ipairs({...}) do
for k, v in pairs(tbl) do
if result[k] ~= nil then
result[k] = nil
end
end
end

return result
end
``````
Then you call that like:

Code: Select all

``````display(difference({key1="Hello", key2="How are you?", key3="What"}, {key1="Poof"}, {key2="Bam"}))
``````
If by numeric tables you mean indexed tables with no explicit keys, it will work the same. Indexed tables are really just a convenience, the above (untested, I just woke up!) would work on any sort of table you decide to pass to it.

Alaran
Posts: 27
Joined: Sat Dec 19, 2009 2:51 pm

### Re: comparing numeric tables

That helped a lot, thanks! And yes, I meant indexed tables.