Is It Possible to Execute a Subroutine Whose Name Is Determined at Run-Time?

Hi, a question about calling dynamically constructed subroutine names.

This exchange:

describes how to execute a macro based on the value of a variable. I'd like to do the same, but calling a dynamically named subroutine with results being passed in (e.g., var1, var2) and back (varResult). I assume "do script " works the same for subroutines, but how do I specify the parameter passing in Applescript? This describes getting and setting KM variables in Applescript, but I'm unsure what to set where.

Any ideas?

You can build the XML for an action that executes a subroutine, and then you can execute the XML.

Here's what the XML looks like (Peter would tell you this is subject to change without notice, so just be aware of that):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">

The only things you need to change are the value of the MacroUID, the Parameters, and the ResultVariable (if relevant). The ActionUID, doesn't matter, and may actually not be needed although it works fine with it present.

I can give you the code to actually execute the XML, if you want to go this direction.

1 Like

Thanks, @DanThomas!

I've been mulling this over for a few days and am a little uncomfortable with the idea of building and sharing something built on an unsupported feature ("subject to change without notice"). [FWIW, a smaller issue with this approach is that I'd need to derive the UUID from the dynamically created subroutine's name, but I suspect that's solvable.]

Hopefully Peter will add an enhancement someday to allow a subroutine to be specified by a variable (though a real subroutine would need to also be specified to serve as a template for parameters to pass). It probably isn't urgent, though, because an easy workaround is to use a global Dictionary to carry the parameters around and use dynamically invoked macros instead of subroutines to perform the operations. I'm going to go with this solution for now.

Thanks again!!

1 Like