Re: copy & set statements
Re: copy & set statements
- Subject: Re: copy & set statements
- From: Nigel Garvey <email@hidden>
- Date: Tue, 23 Oct 2001 14:08:50 +0100
Timothy Bates wrote on Tue, 23 Oct 2001 11:00:42 +1000:
>
I believe the information below ...
[ie. my assertion that a handler deals with the original of a passed list
unless steps are taken to avoid this]
>
... is not correct?
>
>
set theCat to {"woody", "hungry"}
>
>
myHandler(theCat)
>
return theCat
>
>
-->>{"woody", "hungry"}
>
>
on myHandler(myList)
>
set myList to "a"
>
end myHandler
This doesn't actually do anything demonstrative. The handler merely sets
its local parameter variable to something other than the list. However,
change an item *within* the list:
on myHandler(myList)
set item 1 of myList to "a" -- make a change within the list
end myHandler
set theCat to {"woody", "hungry"}
myHandler(theCat)
return theCat
-->>{"a", "hungry"}
Change the handler to:
on myHandler(myList)
copy myList to myList -- create a duplicate list
set item 1 of myList to "a" -- make a change within the duplicate
end myHandler
set theCat to {"woody", "hungry"}
myHandler(theCat)
return theCat
-->>{"woody", "hungry"}
>
To get the behaviour implied (where a handler deals with the original copy
>
of a list), you need to say
>
>
set theCat to {"woody", "hungry"}
>
>
myHandler()
>
>
theCat
>
>
on myHandler()
>
global theCat
>
set theCat to "a"
>
end myHandler
This of course sets the *original* variable to point to something other
than the list. The list itself is entirely unaffected - except that it's
now inaccessible.
>
On 22/10/01 11:17 PM, "Nigel Garvey" <email@hidden>
>
Nigel Garvey wrote on Sun, 21 Oct 2001 15:54:21 +0100:
>
>
>
>> This is something to remember when passing a list or a record as a
>
>> parameter to a handler. The local variable inside the handler is a local
>
>> copy of the pointer to the original structure, not a local copy of the
>
>> structure itself. If you want to fool around with the structure's innards
>
>> and still have the original intact when the handler returns, use the
>
>> 'copy' comand first:
>
>>
>
>> on myHandler(myList)
>
>>
>
>> -- Reassign the variable to a local copy of the list
I retracted this linguistic convenience in a later post. "... a local
copy of the list" should read "... a duplicate of the original list,
which is created by the handler and accessed by a local variable, but
which (like all created values) continues to exist after the handler
returns and which is accessible outside the handler if the pointer is
passed back."
on myHandler(myList)
copy myList to myList
set item 1 of myList to "a"
return myList
end myHandler
set theCat to {"woody", "hungry"}
myHandler(theCat)
set theDog to the result
return {theDog, theCat}
-->>{{"a", "hungry"}, {"woody", "hungry"}}
NG