Difference between revisions of "Module:TableTools"

Jump to navigation Jump to search
reinstate shallowClone - saw a use for it in p.complement - and write p.valueComplement
en>Mr. Stradivarius
(better error message for the set functions)
en>Mr. Stradivarius
(reinstate shallowClone - saw a use for it in p.complement - and write p.valueComplement)
Line 52: Line 52:
return false
return false
end
end
end
--[[
------------------------------------------------------------------------------------
-- shallowClone
--
-- This returns a clone of a table. The value returned is a new table, but all
-- subtables and functions are shared. Metamethods are respected, but the returned
-- table will have no metatable of its own.
------------------------------------------------------------------------------------
--]]
function p.shallowClone(t)
local ret = {}
for k, v in pairs(t) do
ret[k] = v
end
return ret
end
end


Line 264: Line 281:
local tn = select(lim, ...)
local tn = select(lim, ...)
checkType('complement', lim, tn, 'table')
checkType('complement', lim, tn, 'table')
local ret = {}
local ret = p.shallowClone(tn)
for k, v in pairs(tn) do
ret[k] = v
end
-- Remove all the key/value pairs in t1, t2, ..., tn-1.
-- Remove all the key/value pairs in t1, t2, ..., tn-1.
for i = 1, lim - 1 do
for i = 1, lim - 1 do
Line 276: Line 290:
ret[k] = nil
ret[k] = nil
end
end
end
end
return ret
end
--[[
------------------------------------------------------------------------------------
-- valueComplement
--
-- This returns an array containing the relative complement of t1, t2, ..., in tn.
-- The complement is of values only. This is equivalent to all the values that are
-- in tn but are not in t1, t2, ... tn-1.
------------------------------------------------------------------------------------
--]]
function p.valueComplement(...)
local lim = select('#', ...)
if lim < 2 then
error("too few arguments to 'valueComplement' (minimum is 2, received " .. lim .. ')', 2)
end
local isNan = p.isNan
local ret, exists = {}, {}
for i = 1, lim - 1 do
local t = select(i, ...)
checkType('valueComplement', i, t, 'table')
for k, v in pairs(t) do
if not isNan(v) then
-- NaNs cannot be table keys, and they are also unique so cannot be equal to anything in tn.
exists[v] = true
end
end
end
local tn = select(lim, ...)
checkType('valueComplement', lim, tn, 'table')
for k, v in pairs(tn) do
if isNan(v) or exists[v] == nil then
ret[#ret + 1] = v
end
end
end
end
Anonymous user

Navigation menu