Editing Module:TableTools
Jump to navigation
Jump to search
The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then publish the changes below to finish undoing the edit.
Latest revision | Your text | ||
Line 72: | Line 72: | ||
-- NaNs can't be table keys, and they are also unique, so we don't need to check existence. | -- NaNs can't be table keys, and they are also unique, so we don't need to check existence. | ||
ret[#ret + 1] = v | ret[#ret + 1] = v | ||
else | |||
if not exists[v] then | |||
ret[#ret + 1] = v | |||
exists[v] = true | |||
end | |||
end | end | ||
end | end | ||
Line 378: | Line 380: | ||
------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ||
local function _deepCopy(orig, includeMetatable, already_seen) | local function _deepCopy(orig, includeMetatable, already_seen) | ||
-- Stores copies of tables indexed by the original table. | |||
already_seen = already_seen or {} | |||
-- | |||
local copy = already_seen[orig] | local copy = already_seen[orig] | ||
if copy ~= nil then | if copy ~= nil then | ||
return copy | return copy | ||
end | end | ||
if type(orig) == 'table' then | |||
copy = {} | |||
for orig_key, orig_value in pairs(orig) do | |||
copy[_deepCopy(orig_key, includeMetatable, already_seen)] = _deepCopy(orig_value, includeMetatable, already_seen) | |||
end | |||
already_seen[orig] = copy | |||
if includeMetatable then | |||
local mt = getmetatable(orig) | |||
if mt ~= nil then | |||
local mt_copy = _deepCopy(mt, includeMetatable, already_seen) | |||
setmetatable(copy, mt_copy) | |||
already_seen[mt] = mt_copy | |||
end | |||
end | end | ||
else -- number, string, boolean, etc | |||
copy = orig | |||
end | end | ||
return copy | return copy | ||
end | end | ||
Line 407: | Line 411: | ||
function p.deepCopy(orig, noMetatable, already_seen) | function p.deepCopy(orig, noMetatable, already_seen) | ||
checkType("deepCopy", 3, already_seen, "table", true) | checkType("deepCopy", 3, already_seen, "table", true) | ||
return _deepCopy(orig, not noMetatable, already_seen | return _deepCopy(orig, not noMetatable, already_seen) | ||
end | end | ||
Line 460: | Line 464: | ||
-- inArray | -- inArray | ||
-- | -- | ||
-- Returns true if | -- Returns true if valueToFind is a member of the array, and false otherwise. | ||
------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ||
function p.inArray( | function p.inArray(arr, valueToFind) | ||
checkType("inArray", 1, | checkType("inArray", 1, arr, "table") | ||
-- if | -- if valueToFind is nil, error? | ||
for _, v in ipairs(arr) do | |||
if v == valueToFind then | |||
return true | |||
end | end | ||
end | end | ||
return false | return false | ||
end | end | ||
return p | return p |