lua函数--克隆函数clone()

--[[
-- 深度克隆一个值
-- example:
-- 1. t2是t1应用,修改t2时,t1会跟着改变
    local t1 = { a = 1, b = 2, }
    local t2 = t1
    t2.b = 3    -- t1 = { a = 1, b = 3, } == t1.b跟着改变
    
-- 2. clone() 返回t1副本,修改t2,t1不会跟踪改变
    local t1 = { a = 1, b = 2 }
    local t2 = clone( t1 )
    t2.b = 3    -- t1 = { a = 1, b = 3, } == t1.b不跟着改变
    
-- @param object 要克隆的值
-- @return objectCopy 返回值的副本
--]]
function clone( object )
    local lookup_table = {}
    local function copyObj( object )
        if type( object ) ~= "table" then
            return object
        elseif lookup_table[object] then
            return lookup_table[object]
        end
        
        local new_table = {}
        lookup_table[object] = new_table
        for key, value in pairs( object ) do
            new_table[copyObj( key )] = copyObj( value )
        end
        return setmetatable( new_table, getmetatable( object ) )
    end
    return copyObj( object )
end
浅拷贝修改拷贝的某个键对应的值并不影响原始的表的键对应值(只能作用于第一层,如果多层嵌套就会导致原始表被修改)

--- Deep copies a table into a new table.
-- Tables used as keys are also deep copied, as are metatables
-- @param orig The table to copy
-- @return Returns a copy of the input table
local function deep_copy(orig)
  local copy
  if type(orig) == "table" then
    copy = {}
    for orig_key, orig_value in next, orig, nil do
      copy[deep_copy(orig_key)] = deep_copy(orig_value)
    end
    setmetatable(copy, deep_copy(getmetatable(orig)))
  else
    copy = orig
  end
  return copy
end

--- Copies a table into a new table.
-- neither sub tables nor metatables will be copied.
-- @param orig The table to copy
-- @return Returns a copy of the input table
local function shallow_copy(orig)
  local copy
  if type(orig) == "table" then
    copy = {}
    for orig_key, orig_value in pairs(orig) do
      copy[orig_key] = orig_value
    end
  else -- number, string, boolean, etc
    copy = orig
  end
  return copy
end

猜你喜欢

转载自my.oschina.net/robslove/blog/1649403
今日推荐