Rhiannon Rhiannon -3 years ago 167
AppleScript Question

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
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?

Answer Source

You have to define SDEF-based terminology for your command for this to work (which in turn means mucking about with XML and script bundles and potentially creating terminology conflicts, and so on). It's supposed to make AppleScript libraries friendlier to use, but it's really just a waste of everyone's time.

It's simplest just to use normal positional parameters and just have the user pass missing value for 'optional' arguments, which your handler can check for:

set theResult to Create("stuff", "this")
set theResult to Create("stuff", missing value)
set theResult to Create(missing value, missing value)

on Create(thestring, info)
    if thestring is missing value then set thestring to "stuff"
    set present to info is not missing value
    return {present, thestring}
end Create

or else have your handler take a single record as its parameter then concatenate that with a record of default properties:

set theResult to Create for {thestring:"stuff", info:"this"}
set theResult to Create for {thestring:"stuff"}
set theResult to Create for {}

on Create for args
    set args to args & {info:missing value, thestring:"stuff"}
    set present to info is not missing value
    return {present, thestring of args}
end Create

Neither solution is ideal; but isn't true of everything in AppleScript?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download