Button Button Button

Next

This function recursively copies a table's contents, and ensures that metatables are preserved. That is, it will correctly clone a pure Lua object.

Author: Anonymous user

License: MIT/X11 Tags: table copy

Snippet

function deepcopy(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 = deepcopy(v)
        end
        res[k] = v
    end
    setmetatable(res,mt)
    return res
end

Related Snippets


Revision 000003 by sdonovan; created Mon, 21 Sep 2009 07:28:47 +0000

1 comments

razbivamivki on 2013-10-08 00:42:56

Hey thanks for that snippet. I added a little thing that I thought made it more useful, that would compare the entire metatables:

if not ignore_mt then
    local mt1,mt2 = getmetatable(t1),getmetatable(t2)
    if not deepcompare(mt1,mt2) then return false end
end

Add a Comment