Matt's Mind

Wednesday, December 28, 2005

AppleScript ... argh!

I just spent more than an hour wrestling with AppleScript, a language that is supposedly easy to use. Well maybe it is easy read, but it's not necessarily easy to understand.

Quick quiz - what do you think the following prints?:

set ch to "."

if ch ≠ "." then
log "not a dot"
else
log "a dot"
end if

A cigar if you went with "a dot". Now, what will this print?

repeat with ch in characters of "a."
if ch ≠ "." then
log "not a dot"
else
log "a dot"
end if
end repeat

You'd think that since I just wrapped the previous example inside a repeat statement over the characters of "a." that you'd get "not a dot" and "a dot". I'm sure that by now you will have guessed that this is not what you get, or I wouldn't be whinging. In fact you get "not a dot" twice. After reading the AppleScript docs regarding characters, strings, loops and boolean operators I'm still stumped.

The solution? Add this after the "repeat":

set ch to first character of ch

This makes me think that this is some sort of variable type issue, but I really can't be assed spending any more time on this.

2 Comments:

  • Yeah, the repeat loop gets everyone. 'ch' is not the variable itself in this case, it's merely a reference to it. You can coerce or query the reference, but you can't do direct comparisons with it, only its contents. In fact, you can address its contents as such: "ch's contents"

    By Anonymous Anonymous, at 12:40 pm  

  • Now I wouldn't have guessed that one, although I assume the reference allows character replacement, etc. Thanks.

    I really want to like AppleScript: it's a great idea to have a cross-app scripting language built into the OS. But I think Apple may have out-clevered itself with the "like english" concept — I've never programmed in a language where I'm less sure of what any particular statement is going to do.

    By Blogger Matthew Phillips, at 5:45 pm  

Post a Comment

<< Home