DekGenius.com
[ Team LiB ] Previous Section Next Section

15.6 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:

round random number rounding up -- compile-time error

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 error
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
        the frontmost of process item 1 of L -- error
end tell

This runs fine:

tell application "System Events"
        set L to name of every process
        the 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.

    [ Team LiB ] Previous Section Next Section