set originalList = [ 1, 2, 3 ] set copyList = originalList add copy, 4 put originalList -- [ 1, 2, 3, 4 ]If you want to make a duplicate copy of a list containing only numbers, a quick way is to do this:
set copy = originalList * 1The copy thus created will point to a new set of items all its own rather than to the same set as originalList, and the two lists can then be modified independently.
Why does this work? Well, arithmetic operations applied to lists map across the whole list, and produce a new list as a result:
put ( 2 * [ 1, 2, 3 ] ) -- [ 2, 4, 6 ]Multiplying by one is an identity operation that leaves the content values unchanged, but still generates a new "results" list.
However, if you apply this to items which *aren't* integers, they'll mostly be treated as if they are (since all data, more or less, is internally represented by numbers), and your data will get mangled:
put 1 * ["abc", #blah, birth(script "blah") ] -- [11374992, 534, 0]A more general way to duplicate a list would be to use a handler like:
-- handler returning a duplicate copy of a linear list
-- this version recursively calls itself to copy items in aList
-- that are themselves lists, so these too will be duplicates
-- child objects in the list will still be shared by both the source
-- and duplicate lists, however, since there's no sensible way to
-- duplicate objects of unknown provenance (unless you provide
-- all your parents with their own "duplicate" methods...)
on duplicate aList
if not listP( aList ) return aList
set retList = []
repeat with x in aList
if listP(x) then add retList, duplicate(x) else add retList, x
end repeat
return retList
end duplicate