5.5. Blocks
A block
is one or more lines of code demarcated from its surroundings as having a separate nature or purpose. A block is announced by a line stating what type of block it is; then comes the code of the block; and finally the block is terminated by a line starting with the keyword end. Blocks can occur within blocks.
It's very easy to spot a block in AppleScript code, because in decompiled code its lines are indented from the announcement line and the termination line. For example:
myHandler( )
on myHandler( )
repeat 3 times
display dialog "Howdy"
end repeat
end myHandler
That code contains two blocks. One is announced with the on myHandler line, and is terminated by the end myHandler line; everything in between them is the code of that block. That code consists of another block, announced with the repeat line and terminated by the end repeat line; the line of code in between them is the code of that block.
In this book I frequently refer to such blocks by their announcement keyword; for example, I might say "a repeat block."
Some blocks (just two, actuallytell blocks and if blocks) have single-line variants. This permits some rather twisted condensed syntax. For example:
tell application "Finder"
if exists folder "Mannie" then
reveal folder "Mannie"
end if
end tell
You can reduce one or both of those blocks to a single line. So, this is legal (but I never talk this way, and I don't recommend you do either):
tell application "Finder" to if exists folder "Mannie" then
reveal folder "Mannie"
end if
| When typing a block, don't bother to type the
name of the block a second time in the end line. Just type end for that line; the compiler will fill in the name of the block. (For example, don't type end repeat; just type end, on a line by itself, and the compiler will see that this corresponds to a preceding repeat line and will fill in the full end repeat for you.) This is not just a time-saving device; it's also a way to ensure that your blocks are structured correctly. |
|
The only blocks you can make in AppleScript are those for which keywords are supplied; you cannot indent arbitrarily for clarity, as you can in UserTalk or C. So, for example, in UserTalk you can say this:
local (x)
bundle
x = 4
msg (x)
The keyword bundle here does nothing except to allow some code to be indented for clarity. It also provides a further level of local scope. In AppleScript the scoping issue doesn't arise, but a way of indenting for clarity might still be nice. To achieve it you would need to misuse an existing block type. For example:
local x
repeat 1 times
set x to 4
end repeat
display dialog x
|