Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoHotkey warns that a local variable has the same name as a global variable when accessing global variable from a function

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?

like image 598
Stevoisiak Avatar asked Oct 26 '25 09:10

Stevoisiak


1 Answers

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.

like image 136
Stevoisiak Avatar answered Oct 29 '25 05:10

Stevoisiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!