global-variablesautohotkeycompiler-warnings

AutoHotkey warns that a local variable has the same name as a global variable


Any time I try accessing a global variable from an AutoHotkey function with #warn enabled, I'm shown a warning prompt saying my local variable has the same name as a global variable.

This warning only seems to affect functions. Accessing the variable from a hotstring doesn’t raise any warnings.

#Warn
myString := "Hello, world!"

DisplayString() {
   MsgBox %myString%   ; Warning: local variable
}

^j::
   MsgBox, %myString%  ; Perfectly valid!
Return

Why does accessing a global variable from a function trigger a warning?


Solution

  • When using #Warn, global variables should be explicitly declared as global to prevent ambiguity. This can be done in one of three ways.

    Declare the variable as global prior to use

    myString := "Hello, world!"
    DisplayString()
    {
        global myString  ; specify this variable is global
        MsgBox %myString%
    }
    

    Assume-global mode inside the function

    myString := "Hello, world!"
    DisplayString()
    {
        global  ; assume global for all variables accessed or created inside this function
        MsgBox %myString%
    }
    

    Use a super-global variable

    global myString := "Hello, world!" ; global declarations made outside a function
                                       ; apply to all functions by default
    DisplayString()
    {
        MsgBox %myString%
    }
    

    For more information about global variables, refer to the official AutoHotkey documentation.