lua-users home
lua-l archive

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


Careful there-- a table with a circular reference will send your code into an 
infinite loop. Check out the serialization code on the Wiki; it's pretty 
close to deep copy, and could easily be adapted.

also, is there really a need to deep-copy strings, given that they're 
immutable?

Ben

On Tuesday 06 May 2003 03:03 pm, Brad Olson wrote:
> 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

-- 
A man either lives life as it happens to him, meets it head-on and
licks it, or he turns his back on it and starts to wither away.
		-- Dr. Boyce, "The Menagerie" ("The Cage"), stardate unknown