Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameters in AppleScript handlers

The Applescript documentation says that as of Yosemite, parameters for handlers can be made optional.

From the section 'Parameter Specifications':

Labeled parameters may be declared with a default value by following the formal parameter name with :literal. Doing so makes the parameter optional when called. For example, this declares a make handler with a default value for the with data parameter:

on make new theClass with data theData : missing value

This handler can now be called without supplying a with data parameter; the handler would see theData set to the specified default missing value, which it could then test for and handle appropriately.

So, being in need of a handler with optional parameters, I tried to create one. I have got this far:

set theResult to Create of me given the string:"stuff", info:"this"

on Create given info:missing value, thestring:"stuff"
    if info is missing value then
        set present to false
    else
        set present to true
    end if
    return {present, thestring}
end Create

which compiles, but gives me the error 'The variable thestring is not defined.'

If I call it with only one parameter:

set theResult to Create of me given thestring:"stuff"

I receive the error: 'The info parameter is missing for Create.' i.e. the parameter isn't optional after all.

How can I get optional parameters working in Applescript handlers?

like image 250
Rhiannon Avatar asked Mar 14 '23 12:03

Rhiannon


1 Answers

In order to take advantage of optional labeled parameters, the handler definition MUST assign a default value to the parameter(s) you want to be optional. Then, when the caller does not supply that labeled parameter, the default value is used.

Here is an example using user-defined labels, which I find clearer than the magic AppleScript-defined labels (of, by, for, etc.)

SayWhat given greeting:"Hola", farewell:"Adios"
SayWhat given greeting:"Aloha"
SayWhat given farewell:"Ciao"

on SayWhat given greeting:strGreeting : "Hello", farewell:strFarewell : "Goodbye"
    log "You say " & strGreeting & "; I say " & strFarewell
end SayWhat

(*You say Hola; I say Adios*)
(*You say Aloha; I say Goodbye*)
(*You say Hello; I say Ciao*)
like image 135
Ron Reuter Avatar answered Mar 27 '23 18:03

Ron Reuter