Lua: Perfect Clone Function, why not?

This is the question I have always wondered why this is not possible. Why can't there be a perfect cloning function? There is no table.copy function in Lua 5.3, which I believe handles all problems / cases.

With various cloning functions, I meant things like this (shallow, deep, recursive, etc ...) ...

function deep (t) -- deep-copy a table
    if type(t) ~= "table" then return t end
    local meta = getmetatable(t)
    local target = {}
    for k, v in pairs(t) do
        if type(v) == "table" then
            target[k] = clone(v)
        else
            target[k] = v
        end
    end
    setmetatable(target, meta)
    return target
end

function shallow (t) -- shallow-copy a table
    if type(t) ~= "table" then return t end
    local meta = getmetatable(t)
    local target = {}
    for k, v in pairs(t) do target[k] = v end
    setmetatable(target, meta)
    return target
end

function copy1(obj)
  if type(obj) ~= 'table' then return obj end
  local res = {}
  for k, v in pairs(obj) do res[copy1(k)] = copy1(v) end
  return res
end


function copy2(obj)
  if type(obj) ~= 'table' then return obj end
  local res = setmetatable({}, getmetatable(obj))
  for k, v in pairs(obj) do res[copy2(k)] = copy2(v) end
  return res
end

function copy3(obj, seen)
  if type(obj) ~= 'table' then return obj end
  if seen and seen[obj] then return seen[obj] end
  local s = seen or {}
  local res = setmetatable({}, getmetatable(obj))
  s[obj] = res
  for k, v in pairs(obj) do res[copy3(k, s)] = copy3(v, s) end
  return res
end

      

Sources: https://gist.github.com/MihailJP/3931841 and https://gist.github.com/tylerneylon/81333721109155b2d244

Can anyone explain why the ideal clone or copy function cannot be done?

+3


source to share


1 answer


Extend to @lhf perfect note. I think this has been discussed several times in the Lua maillist, and I would say there are two reasons for this: (1) what is ideal and reasonable for one case is overkill for another; (2) due to metamethods, upvalues ​​and circular references, it is difficult to cover different cases perfectly. For example, imagine you are providing a proxy table using metamethods. Now, after cloning two tables, the same proxy table is used, and everything stored in one is visible to the other. Is this a "perfect" clone or not?

On a more philosophical, but still relevant note. Perfection is difficult to achieve due to the external relationships that objects have (and clones may need to keep them or not). You have a home. Likewise, does your ideal clone own the same home? Do you now have 50% of your home? How about a third clone? Or you are happily married. How about your clone? Should I clone my spouse as well? Where is the line between perfect and imperfect in this case?



By the time you care about the difference between deep and shallow copies, you can probably write your own function.

+5


source







All Articles