lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dear fellow Luites (Luan~os? my Portugese lacks),

Looking for a way to do deep copy, I whipped this up. It's very Lisp-ish. It makes some assumptions about how best to copy certain types. 

You experts, please check it out. Did I assume right about what can and cannot be copied?

---clone( SomeObject): make a deep copy of any object.
--@param A: the object to clone.
--@return a deep copy of the object or nil if impossible to copy
function clone(A)
  local T = type(A)
  if T == "string" then return string.sub(A,1)
  elseif T == "number" or T == "boolean" or T == "function" then  --does function need to be handled differently?
    local B = A  --do I have to do this or will (return A) return a copy 
    return B
  elseif T=="table" then
    local Build={}
    local function cloneItem(i,v)
      Build[i] = clone(v)
    end
    table.foreach( A, cloneItem)
    return Build
  else
    --far as I know we can't copy userdata or threads, and nil is nil. These are my big assumptions.
    return nil
  end
end

--Brad Olson
--executive@att.net 
--05/06/2003 at 6:00:15 PM