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

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

t()

Inspired by

See also