Satimage Previous | Next
Structures: if, repeat, try
Home Documentation Smile Smile Tutorial About AppleScript Structures: if, repeat, try  
if
if is for programming a conditional execution. Enclose the boolean expression between parentheses.
set x to 1.0
if (class of x is integer) then
    set s to "i=" & x
else if (class of x is real) then
    set s to "r=" & x
else
    set s to "s=" & x
end if
msg(s)


Import script
The else if and else parts are optional.
repeat
repeat is for executing a given block several times. The syntax is like below.
set theList to {2, 4, 6, 8}
set x to 0
repeat with i from 1 to (count theList)
    set x to x + (get item i of theList)
end repeat
msg(x)


Import script
try: error management
For a reason or another, some line in your script may trigger an error - for instance, you are attempting to read a non-existing file. To catch the errors in a given block of your script, encapsulate the lines with try ... end try. Information about the error is available, namely an error number and an error message, if you insert a on error line as shown below.
set x to 1
set y to 0
try
    x / y
on error s number n
    postit ("error number " & n & ": " & s)
end try
Since the try ... end try mechanism is so comfortable, you may use it as a branching mechanism. To trigger an error in your script, use the error AppleScript verb, or Smile's throwerror verb which is faster.
throwerror s number n
try
    set x to 1
    throwerror "stop" number 1
    set x to 2
on error s number n
    postit ("error number " & n & ": " & s)
    quietmsg(x)
end try


Import script
Copyright ©2008 Paris, Satimage