PDA

View Full Version : Repeat loop weirdness




kryten2
Aug 9, 2012, 06:30 PM
I noticed some odd behaviour when copying some code from ScriptEditor to a Run Applescript action in Automator.

This example code runs fine in Scripteditor :

set numberList to {"1", "2", "3"}
repeat with i from 1 to number of items in numberList
set this_item to item i of numberList
display dialog this_item giving up after 3
end repeat


When copied to the Run Applescript action in Automator it changes into this when compiled :

set numberList to {"1", "2", "3"}
repeat with i from 1 to number of items of numberList
set this_item to item i of numberList
display dialog this_item giving up after 3
end repeat

The "of" between number and items is no longer bold and the "in" changed to of. When run it errors with the following message :

Syntax Error

No result was returned from some part of this expression.

The solution is to change the code to this :

set numberList to {"1", "2", "3"}
repeat with i from 1 to count of items of numberList
set this_item to item i of numberList
display dialog this_item giving up after 3
end repeat


Why does this happen? Can someone shed some light on this? Thanks.



chown33
Aug 9, 2012, 06:40 PM
Why not just switch to the more concise:
repeat with each_item in numberList
display dialog each_item giving up after 3
end repeat


The form is:
repeat with listVar in someList

Search for Repeat with listVar in this doc:
http://oreilly.com/catalog/aplscptian/chapter/ch07.html


EDIT
If you insist on using counted loops, consider using the shorter:
count of listName

Reference doc:
https://developer.apple.com/library/mac/#documentation/applescript/conceptual/applescriptlangguide/reference/aslr_cmds.html

It's superfluously prolix to write:
count of items of listName

kryten2
Aug 9, 2012, 08:12 PM
Thanks for the reply chown33. Clear as ever. Had to lookup the meaning of superfluously prolix. Got it now.