Search code examples
command-lineparametersautohotkeyargs

Autohotkey / AHK - Param %1% not accessible within a function


I'm having a problem with accessing the %1% ( Startup Param that has been passed to the Script by the console ) in Autohotkey.

When I use the following code (outside of a function):

Msgbox %1%

I get the output of the Param that has been passed to the Script. But as soon as I use the following Code:

HelloWorld() {
    Msgbox %1% 
}
HelloWorld()

The output is empty.

I also tried to assign %1% to a global variable, or to pass it to the Function as a parameter but it didn't work for me neither.

Thank you


Solution

  • I believe the command line parameter variables are considered global variables, so in order to use them in a non-expression context inside a function you have to declare them as global:

    HelloWorld() {
        global 1
        Msgbox %1% 
    }
    HelloWorld()
    

    It gets even more confusing once you want to use them in expressions (such as using % in the text argument for MsgBox), since they will be treated as numbers so you have to indirectly access them through variables:

    HelloWorld() {
        ;global 1
        ; Neither of these two expressions access the variable named "1"
        ;Msgbox % 1
        ;Msgbox % %1%
    
        ; You have to do this instead:
        p := 1
        MsgBox % %p% ; p is translated to 1 and then "1" is used as a variable name
    }
    HelloWorld()
    

    Note that doing this doesn't require global 1.

    If you're using the newest version of AHK, you instead probably want to use the newly introduced built-in variable A_Args, which is an array that holds the command line parameters. Being built-in, it doesn't have to be declared global, and it ultimately makes the code clearer:

    HelloWorld() {
        MsgBox % "Number of command line args received: " A_Args.Length() "`n"
                 . "First argument: " A_Args[1]
    }
    HelloWorld()