copia profunda lua y copia superficial

Copia superficial modificar el valor correspondiente a una clave de la copia no afecta el valor correspondiente a la clave de la tabla original (solo en el primer nivel, si múltiples niveles de anidamiento harán que la tabla original sea modificada)

Esta copia profunda puede copiar la metatabla de la tabla original al mismo tiempo. Se puede setmetatable(copy, deep_copy(getmetatable(orig)))eliminar si no se permite .

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

 

Supongo que te gusta

Origin blog.csdn.net/Momo_Da/article/details/102785525
Recomendado
Clasificación