Section 15.7. Parentheses


15.7. Parentheses

Parentheses may be used to determine the order of operations at runtime:

 3 + 4 * 2 -- 11 (3 + 4) * 2 -- 14 

Parentheses can also help determine the order of interpretation of vocabulary at compile time. Thus they can make the difference between successful compilation and failed compilation. For example, this compiles fine, because all the expressions are legal:

 set r to random number round r rounding up 

Now try to save a line by combining them, and you get this ungrammatical and mysterious error:

 round random number rounding up -- compile-time error: A application constant [sic] or consideration can't go after this identifier 

The problem is that random number is a command that can optionally take various labeled parameters, and rounding up isn't one of them. Instead of rethinking its interpretation ("So, maybe random number isn't taking any parameters here!"), AppleScript just gives up. You have to help it out, by using parentheses:

 round (random number) rounding up 

Sometimes AppleScript will insert parentheses for you, on compilation. For example, I didn't put any parentheses when I typed this code:

 tell application "System Events"     copy name of every process where it is frontmost to theProc end tell 

But AppleScript did, when it compiled:

 tell application "System Events"     copy (name of every process where it is frontmost) to theProc end tell 

The reason seems to be to delimit a phrase implying a get command. But if you actually use get explicitly here without parentheses, AppleScript refuses to compile at all:

 tell application "System Events"     copy get name of every process where it is frontmost to theProc     -- compile-time error: Expected "into", "to", etc. but found "get" end tell 

The problem seems to be that AppleScript doesn't like the phrase copy get, which is two commands in a row. If you add the parentheses, AppleScript compiles:

 tell application "System Events"     copy (get name of every process where it is frontmost) to theProc end tell 

Parentheses can also make a difference at runtime. AppleScript will compile this, but it causes an error at runtime:

 tell application "System Events"     set L to name of every process     frontmost of process item 1 of L     -- error: No result was returned from some part of this expression end tell 

This runs fine:

 tell application "System Events"     set L to name of every process     frontmost of process (item 1 of L) end tell 

The moral is: if things don't seem to be working out, try playing with parentheses.




AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net