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( "taptest" )
local deepcopy = require( "deepcopy" )
local same = require( "same" )

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

t()

See also