deepcopy

function deepcopy( tab ) --> copy

Description

Makes a deep copy of the table tab, copies all the keys and values. The metatable will be adopt.

Parameters

tab

The table that should be copied.

Return Values

copy

A new table.

Code

--ZFUNC-deepcopy-v1
local function deepcopy( tab ) --> copy
   if type( tab ) ~= "table" then return tab end
        local mt = getmetatable( tab )
        local copy = {}
        for k, v in pairs( tab ) do
                if type( v ) == "table" then v = deepcopy( v ) end
                copy[ k ] = v
        end
        setmetatable( copy, mt )
        return copy
end

return deepcopy

Examples

local t = require( "tapered" )
local deepcopy = require( "deepcopy" )

tab = { "abc", "def", { 123, 456 } }
copy = deepcopy( tab )
t.isnt( tab, copy )
t.isnt( tab[ 3 ], copy[ 3 ] )
t.same( tab, copy )

t.done()

See also