Skip to content

table.copy sample doesn't work #23

@SiENcE

Description

@SiENcE

This sample don't work, because of
local mt = getmetatable(t)
and
setmetatable(res,mt)
.

--recursive deep copy
function table.copy(t)
if type(t) ~= 'table' then return t end
local mt = getmetatable(t)
local res = {}
for k,v in pairs(t) do
if type(v) == 'table' then
v = table.copy(v)
end
res[k] = v
end
setmetatable(res,mt)
return res
end

Also this sample doesn't work.

function table.copy(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for index, value in pairs(object) do
new_table[_copy(index)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end

Any hints?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions