Re: set myList to myList & ... and unexpected results
Re: set myList to myList & ... and unexpected results
- Subject: Re: set myList to myList & ... and unexpected results
- From: Matt Neuburg <email@hidden>
- Date: Sun, 24 Jul 2005 09:34:10 -0700
On Sun, 24 Jul 2005 11:09:40 +0100, has <email@hidden> said:
>Ryan Wilcox wrote:
>
>>Perhaps someone here can help me with a puzzle. Run the following code:
>>
>>- --<code language="Applescript>
>>
>>set myList to {}
>>set myItem to {1}
>>
>>set myList to myList & myItem
>>set item 1 of myList to 123
>>
>>set myList to myList & myItem
>>
>>- --</code>
>>
>>The output of this code is {123, 123}, and NOT {123, 1} like I would
>>expect.
>>
>>Could someone explain why I get this result, please?
>
>It's a bug, file a report. The first concatenation returns the right-hand
operand directly instead of creating a new object. Not an issue with immutable
types such as strings, but very bad for mutable objects.
Here's a better statement of the phenomenon (eliminates the self-set in the
third line, which is a confusing red herring):
set emptyList to {} -- first list must be empty
set L1 to {"mannie"}
set L2 to emptyList & L1 -- {"mannie"}
set item 1 of L1 to "jack"
L2 -- {"jack"}
set item 1 of L2 to "moe"
L1 -- {"moe"}
Clearly L2 and L3 have become references to the same thing. As Hamish
implies, it's an optimization gone wrong... :) Do note, however, that the
fact that lists are set by reference is *not* a bug. In other words, you
would not be surprised (if you know the language) if what you'd said was
this:
set L1 to {"moe"}
set L2 to L1
set item 1 of L1 to "jack"
L2 -- {"jack"}
So the surprise is that concatentation to an empty list shortcuts to a
direct set. I suspect that the behavior underlying it is the same as in this
code:
set L1 to {"ho"}
set L2 to {"hi"}
set end of L1 to L2
L1 -- {"ho", {"hi"}}
BUT:
set L1 to {}
set L2 to {"hi"}
set end of L1 to L2
L1 -- {"hi"}, not {{"hi"}}
In that example, we are surprised to see that "set end of" behaves
differently than in the previous example: instead of adding an item that it
is a list, it adds an item that is a string. And, as before, it turns out
that what's really happened is a set by reference:
set L1 to {}
set L2 to {"hi"}
set end of L1 to L2
L1 -- {"hi"}, not {{"hi"}}
set item 1 of L2 to "mannie"
L1 -- {"mannie"}
-- but not the other way round!
set item 1 of L1 to "moe"
L2 -- {"mannie"}
m.
--
matt neuburg, phd = email@hidden, <http://www.tidbits.com/matt/>
A fool + a tool + an autorelease pool = cool!
AppleScript: the Definitive Guide
<http://www.amazon.com/exec/obidos/ASIN/0596005571/somethingsbymatt>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Applescript-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden