NS.X. NS.X. - 1 month ago 18
AppleScript Question

How to invoke a handler stored in a variable in Applescript

New to AppleScript, it looks variables can be set to scripts or handlers:

on Foo()
log "Foo"
end Foo

on Bar()
log "Bar"
end Bar

set myHandlers to {Foo, Bar}
set x to the first item in myHandlers
log x -- <<handler Foo>>


Now how do I invoke 'x'? Couldn't find this information in official docs; tried some keywords like "run", "exec", all not working.

foo foo
Answer

Don't do that – it's an undefined behavior and doesn't work as expected. (AppleScript handlers are not closures.) The correct way is to wrap each handler in a script objects and assign those:

script Foo
  on doit()
    log "Foo"
  end doit
end script

script Bar
  on doit()
    log "Bar"
  end doit
end script

set myHandlers to {Foo, Bar}
set x to the first item in myHandlers
x's doit() -- logs "Foo"

There are some examples here [1] which you may find helpful; e.g. see the List library's sort list command and the Text library's search text commands, both of which take optional parameters that use this technique to enable user-customizable behaviors.


[1] BTW, also feel free to dupe my Radar ticket requesting Apple include those libraries in 10.13; the more requests they get the more likely they are to do it.