shallowcopy

function shallowcopy( tab ) --> copy

Description

Makes a copy of the table tab, copies only the toplevel keys and values. The metatable will not be handled.

Parameters

tab

The table that should be copied.

Return Values

copy

A new table.

Code

--ZFUNC-shallowcopy-v1
local function shallowcopy( tab ) --> copy
   if type( tab ) ~= "table" then return tab end

   local copy = {}
   for k, v in pairs( tab ) do
      copy[ k ] = v
   end

   return copy
end

return shallowcopy

Examples

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

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

t.done()

Inspired by

See also