Jump to content

Module:TableTools: Difference between revisions

add getIntersection function
m>Mr. Stradivarius
(better variable name - getUnion deals with all tables, not just arrays)
m>Mr. Stradivarius
(add getIntersection function)
Line 38: Line 38:
--
--
-- This returns the union of the values of n tables, as an array. For example, for
-- This returns the union of the values of n tables, as an array. For example, for
-- the tables {1, 3, 4, 5, foo = 7} and {2, 3, 5, bar = 6}, getUnion will return
-- the tables {1, 3, 4, 5, foo = 7} and {2, bar = 3, 5, 6}, getUnion will return
-- {1, 2, 3, 4, 5, 6, 7}.
-- {1, 2, 3, 4, 5, 6, 7}.
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
Line 54: Line 54:
end
end
table.sort(ret)
table.sort(ret)
return ret
end
end
--[[
------------------------------------------------------------------------------------
-- getIntersection
--
-- This returns the intersection of the values of n tables, as an array. For
-- example, for the tables {1, 3, 4, 5, foo = 7} and {2, bar = 3, 5, 6},
-- getIntersection will return {3, 5}.
------------------------------------------------------------------------------------
--]]
function p.getIntersection(...)
local tables = {...}
local vals, ret = {}
local lim = #tables
for _, t in ipairs(tables) do
for k, v in pairs(t) do
local valCount = vals[v] or 0
vals[v] = valCount + 1
end
end
for val, count in pairs(vals) do
if count == lim then
ret[#ret + 1] = val
end
end
table.sort(ret)
return ret
end


--[[
--[[
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.