Monday, February 27, 2017

#1 2005-10-13 02:45:15 pm

From: Malasa├▒a, Madrid
Registered: 2002-11-20
Posts: 2014

Do exist "functions" in AppleScript?

Yes. They aren't called "functions", but "handlers". Its usage is similar to "functions" in most of languages. You call them, optionally passing parameters, and you get the result from its execution.


--> here, we call the handler
set theDigit to add5(37)
--> result will be 42

--> and this is Mr. Handler
to add5(thisNumber)
   return thisNumber + 5
   --> if the "return" statement is not specified,
   --> it will be returned the result of the last
   --> expression found in the handler
end add5

This was a sample of handler with parameters. If you define a parameter or parameters (thisNumber), you must pass allways a parameter, or the execution will throw an error.

We can also use labeled parameters, which are regular handlers with colorful syntax:


told by "Shakespeare" about "Something smells like teen spirit in Denmark" with drunk
to told by anAuthor about aString with drunk
   if drunk then
       return anAuthor & " wrote while drunk: " & aString
       return anAuthor & " wrote after the breakfast: " & aString
   end if
end told

What I call a "regular" handler (the first exposed example) is also called "handler with positional parameters", which means basically that you must pass the parameters ordered. But its main goal is allways the same.

There are also some special handlers, to handle special events. For example, every script in the scripting world has an explicit or implicit run handler, which contains the code which is executed when the script receives a "run" event (eg, when we hit "run" in our script editor or choose the script in the Script Menu). So:


on run
end run

Is the same as:



Other special handlers with special meanings are quit, open, reopen and idle, etc. More info about handlers, AppleScript Language Guide, pag. 290 in the downloadable pdf.

Finally, you can also use certain apple events to define your handler. For example, a common apple event which can be received by some applications is the GURLGURL apple event. This apple event is sent, eg, when you click a link "mailto" in a web page, and the browser sends your mail client (eg, Eudora) enclosed info in a GURLGURL event. So, you could define your own GURLGURL event and handle the data received:


on ├?┬źevent GURLGURL├?┬╗ someData
   display dialog someData
end ├?┬źevent GURLGURL├?┬╗

* Please, note that GURLGURL will compile as "open location", which is in fact a GURLGURL event defined in Apple's Standard Additions.



Board footer

Powered by FluxBB

[ Generated in 0.034 seconds, 10 queries executed ]

RSS (new topics) RSS (active topics)