How Can I Dynamically Create an AppleScript Command?


(Jim Underwood) #1

I have a sense that this can be done with script objects, but my searches have not turned up how to do this.

I want to use a variable to create an AppleScript command. Can this be done? If so, how?

For example, instead of this, using a bunch of if/then/else if statements with

    if (posInName = "starts with") then
      set oWin to first window whose name starts with winNamePartial
    else if (posInName = "ends with") then
      set oWin to first window whose name ends with winNamePartial
    else
      set oWin to first window whose name contains winNamePartial
    end if

Use this:

    set posInName to "starts with" -- OR "ends with" OR "contains"
    set cmd to "set oWin to first window whose name " & posInName & " winNamePartial
    --- Now execute the command in the "cmd" variable ---

Can this be done?

As a full example, here is my script to get the input variables from Keyboard Maestro, and then use in the script:


tell application "Keyboard Maestro Engine"
  set winNamePartial to getvariable "MWF__WinName"
  set posInName to getvariable "MWF__PosInName"
end tell


tell application "System Events"
  set frontmostApp to name of first item of (processes whose frontmost is true)
  tell process frontmostApp
    
    if (posInName = "starts with") then
      set oWin to first window whose name starts with winNamePartial
    else if (posInName = "ends with") then
      set oWin to first window whose name ends with winNamePartial
    else
      set oWin to first window whose name contains winNamePartial
    end if
    
    --set posInName to "starts with" -- OR "ends with" OR "contains"
    --set cmd to "set oWin to first window whose name " & posInName & " winNamePartial
    
    set value of attribute "AXMain" of oWin to true
  end tell
end tell

(Mark Alldritt) #2

You can assign handler to a variable, and thus make the dispatching of a handler call dynamic:

on handler1()
    return “abc”
End

on handler2()
    return “def”
end

set doIt to handler1

doit() —> “abc”

set doIt to handler2

doIt() —> “def”

(Jonas Whale) #3

Or you can use this old trick (if you don’t care about execution speed):

set oWin to run script "first window whose name" & space & posInName & space & "\"" & winNamePartial & "\""