Module:TableTools: Difference between revisions
From Tardis Wiki, the free Doctor Who reference
add a complement function
(generate an error message when union and intersection functions are called with no arguments) |
(add a complement function) |
||
Line 190: | Line 190: | ||
end | end | ||
ret[#ret + 1] = val | ret[#ret + 1] = val | ||
end | |||
end | |||
return ret | |||
end | |||
--[[ | |||
------------------------------------------------------------------------------------ | |||
-- complement | |||
-- | |||
-- This returns the relative complement of t1, t2, ..., in tn. The complement | |||
-- is of key/value pairs. This is equivalent to all the key/value pairs that are in | |||
-- tn but are not in t1, t2, ... tn-1. | |||
------------------------------------------------------------------------------------ | |||
--]] | |||
function p.complement(...) | |||
local lim = select('#', ...) | |||
if lim == 0 then | |||
error("no arguments passed to 'complement' (minimum is two)", 2) | |||
elseif lim == 1 then | |||
error("only one argument passed to 'complement' (minimum is two)", 2) | |||
end | |||
-- Now we know that we have at least two sets. | |||
local ret = select(lim, ...) | |||
checkType('complement', lim, ret, 'table') | |||
for i = 1, lim - 1 do | |||
local t = select(i, ...) | |||
checkType('complement', i, t, 'table') | |||
for k, v in pairs(t) do | |||
if ret[k] == v then | |||
ret[k] = nil | |||
end | |||
end | end | ||
end | end |