Moving from Microsoft Office VBA to AppleScript:
MacTech's Guide to Making the Transition
Introduction
|
Table of Contents
Page Prev and Page Next buttons at bottom of the page.
|
April, 2007
Page 12
-- code here
end repeat
for “For Each” loops. This should work fine without problems when eachItem is an application object reference, as it usually will be. But you can often go awry if you forget that eachItem in this construction is a reference, not yet evaluated. The = equality operator will behave unexpectedly rigorously in this block:
repeat with eachItem in {1, 2, 3, 4, 5}
if eachItem = 2 then
beep
display dialog (eachItem as string)
exit repeat
end if
end repeat
display dialog (eachItem as string)
No beep is heard, and the dialog displays 5. That's because eachItem never equals 2: it equals 'item 2 of {1,2,3,4,5}'. To avoid dealing with this issue, which you can solve by replacing the second line by
if contents of eachItem = 2 then
(or by other ways of forcing an evaluation of eachItem such as coercion), many people find it simpler just to use
repeat with i from 1 to (count {1, 2, 3, 4, 5})
set eachItem to item i of {1, 2, 3, 4, 5}
if eachItem = 2 then
i.e., a For…Next loop, in all cases.
Note: In VBA if you have "For i = 1 to 5 … Next i", the equivalent of this type of repeat loop, when you drop out of the loop having been round 5 times, the value of i is now 6. In AppleScript, i is 5 on exit from the loop 'repeat with i from 1 to 5'. This will surprise VBA coders who often rely on reading the value of n to see whether a loop was exited normally or by means of an Exit For statement.
exit repeat is the equivalent of Exit For, and gets you out of the block.
Check out the last subsection here – Special AppleScript Features – for two very powerful methods that can replace some repeat loops altogether.
On Error Resume Next/Go To : try…on error…end try
While not identical to VBA's On Error, AppleScript has something similar, but you must frame the section of code in which you want to trap the error with a try…end try block. A simple
try
--code here
end try
is like an On Error Go To line after 'end try' applied to any runtime error that occurs within the block. This code:
try
--code here
on error
--alternate code here
end try
provides an alternative in the event of an error, like On Error Resume Next but which can be located anywhere in your script. A more elaborate
try
--code here
on error errMsg number errNum
if errNum = -1708 then
--alternate code here quoting or parsing the
message
< Previous Page Next Page>
- SPREAD THE WORD:
- Slashdot
- Digg
- Del.icio.us
- Newsvine