lua 深拷貝與淺拷貝

淺拷貝修改拷貝的某個鍵對應的值並不影響原始的表的鍵對應值(只能作用於第一層,如果多層嵌套就會導致原始表被修改)

這個深拷貝可以同時複製原始表的元表。如果不許要可以將setmetatable(copy, deep_copy(getmetatable(orig)))去掉。

--- 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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章