Words of occasional wisdom from Bruce Oakley

Tips and Traps

Links: Tips-Traps | Change Case | Parse Data | Search-Replace
Here are a few time- and trouble-saving tips on traps to avoid in scripting:

Know what the problem is: Most of my scripts do fairly simple things, so I tend not to build in error trapping. Unfortunately, when I make a more involved script, I often still leave out error trapping. If I run the script from Script Editor during testing, I get error messages that help me solve problems. When run from an application’s script menu, though, it will report only “Unknown error” if anything goes wrong. The simple solution: Wrap your code in “try ... on error ... end try” blocks. You can then resolve errors in the “on error” routine or display the full error message that Script Editor provides.

Know your place: Mac OS and applications sometimes count differently: the 27th word to an AppleScript read routine may not be the same item the word processor considers the 27th word in a paragraph.

Know what’s in a name: Variables can refer to things or references to things. I had a lot of trouble in early scripts where I would save a filename to a variable (set thisVariable to “filename.txt”) and then try to “open thisVariable.” It took a long time to get used to the idea that thisVariable was only a text string, not a file reference, and I needed something like “open file whose name is thisVariable.”

Know where you’re going: Use full paths or container specifications, especially with the “make” command. An AppleScript command to “make new file before the beginning” without specifying “beginning of ...” which location/folder/etc. will dutifully overwrite the current desktop!

Know where you came from: When you change system defaults such as the “AppleScript text item delimiters,” be sure to restore them when the immediate task is finished or you may get unintended results in other tasks. Also be aware that if an execution error arises before you restore the default AppleScript text item delimiters, the delimiters will be whatever you have changed them to until you restart the machine. You may be expecting a list of text items to be individual characters and may instead get words, phrases or even blocks of text.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: