arraysautohotkey

How do I send the value of an array variable in Autohotkey?


I'm writing an AutoHotkey script which needs to display the value of an array variable, but it doesn't seem to be working properly.

MyArray := ["one", "two", "three"]

send MyArray[1]     ; "MyArray[1]"
send MyArray%1%     ; "MyArray"
send %MyArray1%     ; <empty>
send % MyArray%1%   ; <empty>
;send %MyArray%1%   ; 'Error: Variable name missing its ending percent sign'
;send %MyArray%1%%  ; 'Error: Empty variable reference (%%)'
;send %MyArray[1]%  ; 'Error: Variable name contains an illegal character'

I've found posts on the AHK forums claiming I can use send %MyArray1% or send % MyArray %1%, but both commands just reference empty variables.

How do I send an array's value in an AutoHotkey script?


Solution

  • Use a single % to force expression mode then surround the array index in square brackets.

    MyArray := ["one", "two", "three"]  ; initialize array
    Send, % MyArray[1]                  ; send "one"
    

    This can be combined with regular text using quotation marks ""

    Send, % "The first value in my array is " MyArray[1]
    

    Expression mode can be used with any command, including MsgBox and TrayTip.

    MsgBox, % MyArray[1]
    Traytip, , % "The first value is " MyArray[1]
    

    See also: