0
votes

When I declare a global variable after #ifwinactive, an error message pop up showing that the variable is not declared.

I have a long script where there are many #ifwinactive ahk_exe xxx. Below those codes, I want to declare a global variable. But that doesn't work. Whenever I run the script, it warns me the global variable is not declared. Here's a brief of my script.

On the top of the script I have these environment settings:

#NoEnv  
#Warn  
SendMode Input 
SetWorkingDir %A_ScriptDir%
SetTitleMatchMode, 2

Then I have many window-specific hotkeys:

#ifwinactive ahk_exe Explorer.EXE
;some hotkeys
#ifwinactive ahk_exe WINWORD.EXE
;some extra hotkeys
;etc.

At the bottom, I try to declare a global variable and this is where the error occurs:

#ifwinactive
a := 1
^p::
    if (a != 1){
        a := 1
    } else {
        a := 0
    }
return 

#if winactive("- YouTube -") and a != 1
    p::msgbox,Yes
#if a = 1 and winactive("- YouTube -")
    p::msgbox,no
#if
1

1 Answers

5
votes

You're declaring the variable a outside of the auto-execute section.
Code execution never actually reaches a := 1, it's stopped when your first hotkey definition is met.
Also, it's not an error, just a warning. Due to how forgiving AHK is, it doesn't actually matter if you don't declare the variable before use. It'll start off with the default value of nothing, which works for your a != 1 check.
Also, after you run the ^p hotkey at least once, it'll behave as intended.

But anyway, to get rid of warning, you'd declare the variable in the auto-execute section of your script (at the top).

And an extra thing to consider:
Don't use #If unless you actually need it. It can cause trouble (as the documentation states), depending on what sort of a script you have.
If a win active check, and a toggle is all you need to check for, I don't think it really warrants usage of #If.