Re: Adding items to a record in a list.
Re: Adding items to a record in a list.
- Subject: Re: Adding items to a record in a list.
- From: Nigel Garvey <email@hidden>
- Date: Sat, 2 Apr 2005 14:20:25 +0100
Paul Berkowitz wrote on Fri, 01 Apr 2005 12:57:50 -0800:
>On 4/1/05 12:29 PM, "Robert Smith" <email@hidden> wrote:
>
>> set r1 to {name:"B", junk:"ab "}
>> set r2 to {name:"A"}
>> set lr to {r1, r2}
>>
>> I want to add a "c" to the end of every 'junk:' item in the list. But
>> those records with no junk: need to get one with just a "c" in it. I do
>> not want to copy the list, only modify it in place. Here is one try:
>>
>> on addc(j)
>> try
>> set junk of j to junk of j & "c"
>> on error number errnum
>> set j to j & {junk:"c"} -- < -- What to put here??
j starts out with the value of the loop variable in the 'repeat with ...
in ...' loop below, and is thus a 'reference' to an item in the list. As
Paul points out, 'set j to ...' only changes the value of j, not of the
item to which j otherwise refers. You can change the value of the item
itself by using the 'contents' operator:
set j's contents to j & {junk:"c"}
The problem with this in a handler is that you then *have* to pass a
reference. The line will error if the handler's called from elsewhere in
the script with a straightforward record parameter. So Paul's approach of
having the handler simply return a value is more flexible.
>> end try
>> end addc
>>
>> repeat with i in lr
>> addc(i)
>> end repeat
>> get lr
>> --> {{name:"B", junk:"ab c"}, {name:"A"}}
>repeat with i from 1 to (count lr)
> set ii to item i of lr
> set item i of lr to addc(ii)
>end repeat
>get lr
>--> {{name:"B", junk:"ab c"}, {name:"A", junk:"c"}}
>
>
>on addc(j)
> try
> set junk of j to junk of j & "c"
> on error number errnum
> set j to j & {junk:"c"}
> end try
> return j
>end addc
Hi, Paul. The line in the handler - 'set junk of j to junk of j & "c"' -
still changes the record in the list directly, no matter whether j is a
reference or a record, since a passed record is "shared data". A 'copy'
command would avoid this if it was felt to be untidy:
on addc(j)
copy j's contents to j -- works with both references and
non-references
try
set junk of j to junk of j & "c"
on error
set j to j & {junk:"c"}
end try
return j
end addc
In this form, the handler only returns a value and can be used either
with the repeat as you wrote it or with:
repeat with i in lr
set contents of i to addc(i)
end repeat
NG
_______________________________________________
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