Module:Shared: Difference between revisions

503 bytes removed ,  17 September 2020
no edit summary
(Copied over some handy shared functions I'll probably need later.)
 
No edit summary
Line 234: Line 234:
end
end
   
   
-- copies the contents of a variable; for copying tables recursively
-- copies the contents of a variable; handy for when you might want to modify an object taken from a data file
-- source: http://lua-users.org/wiki/CopyTable
-- or any other read-only variable
-- pre : orig is the original value
-- Stolen from https://gist.github.com/tylerneylon/81333721109155b2d244
-- post: returns a copy of the original table if orig is of type
function p.clone(orig)
--      table, including all children tables but not metatables;
     if type(obj) ~= 'table' then return obj end
--      otherwise returns whatever is contained in orig
    local res = {}
function p.deepCopy(orig)
    for k, v in pairs(obj) do res[clone(k)] = clone(v) end
     local orig_type = type(orig)
     return res
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[p.deepCopy(orig_key)] = p.deepCopy(orig_value)
        end
        -- cannot copy metatables of tables loaded in by mw.loadData();
        -- stack overflow error if you uncomment the statement below
        -- setmetatable(copy, p.deepCopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
     return copy
end
end
   
   
return p
return p