Task

Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.



The task should show:

 Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.
 Any limitations of the method.
 That the structure and its copy are different.
 Suitable links to external documentation for common libraries.


function _deepcopy(o, tables)
 
  if type(o) ~= 'table' then
    return o
  end
 
  if tables[o] ~= nil then
    return tables[o]
  end
 
  local new_o = {}
  tables[o] = new_o
 
  for k, v in next, o, nil do
    local new_k = _deepcopy(k, tables)
    local new_v = _deepcopy(v, tables)
    new_o[new_k] = new_v
  end
 
  return new_o
end
 
function deepcopy(o)
  return _deepcopy(o, {})
end