Jump to content

Module:TableTools: Difference between revisions

add key/value pair union function
m>Mr. Stradivarius
(fix lim variable in intersection function)
m>Mr. Stradivarius
(add key/value pair union function)
Line 39: Line 39:
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-- union
-- union
--
-- This returns the union of the key/value pairs of n tables. If any of the tables
-- contain different values for the same table key, the table value is converted
-- to an array holding all of the different values.
------------------------------------------------------------------------------------
--]]
function p.union(...)
local ret, trackArrays = {}, {}
for i = 1, select('#', ...) do
local t = select(i, ...)
for k, v in pairs(t) do
local retKey = ret[k]
if retKey == nil then
ret[k] = v
elseif retKey ~= v then
if trackArrays[k] then
local array = ret[k]
array[#array + 1] = v
ret[k] = array
else
ret[k] = {ret[k], v}
trackArrays[k] = true
end
end
end
end
return ret
end
--[[
------------------------------------------------------------------------------------
-- valueUnion
--
--
-- 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
Line 45: Line 77:
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
--]]
--]]
function p.union(...)
function p.valueUnion(...)
local vals, ret = {}, {}
local vals, ret = {}, {}
for i = 1, select('#', ...) do
for i = 1, select('#', ...) do
Line 70: Line 102:
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-- intersection
-- intersection
--
-- This returns the intersection of the key/value pairs of n tables. Both the key
-- and the value must match to be included in the resulting table.
------------------------------------------------------------------------------------
--]]
--[[
------------------------------------------------------------------------------------
-- valueIntersection
--
--
-- This returns the intersection of the values of n tables, as an array. For
-- This returns the intersection of the values of n tables, as an array. For
Line 76: Line 117:
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
--]]
--]]
function p.intersection(...)
function p.valueIntersection(...)
local vals, ret = {}, {}
local vals, ret = {}, {}
local lim = select('#', ...)
local lim = select('#', ...)
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.