Stevoisiak
Stevoisiak

Reputation: 26812

Why is #include breaking global variables?

I have a simple .ahk file which reloads the currently running script any time I press Esc.

; reload-hotkey.ahk

Esc::Reload     ; reload script with Esc

For some reason, importing this file causes global variables to stop working properly.

; test-file.ahk

#Include %A_ScriptDir%\reload-hotkey.ahk    ; This line causes the problem
globalString := "Hello"
^q::
   localString := "World"
   MsgBox '%globalString% %localString'     ; Output: ' World'
Return

If I remove my #include statement, the code works as expected.

; test-file-2.ahk

globalString := "Hello"
^q::
   localString := "World"
   MsgBox '%globalString% %localString%'    ; Output: 'Hello World'
Return

This only happens if my included file includes a hotkey. If the function only includes methods or functions, my code will work as expected.

For reference, I am using AutoHotkey Unicode 32-bit 1.1.26.01.

Why would an #include statement cause global variables to not work properly?

Upvotes: 1

Views: 580

Answers (1)

Jim U
Jim U

Reputation: 3366

Variable definitions must occur before any hotkey or hotstring definitions.

So put the variable definition above the include statement.

globalString := "Hello"
#Include %A_ScriptDir%\reload-hotkey.ahk    ; This line causes the problem

For more information, see the Auto-execute Section in the Autohotkey documentation.

Upvotes: 2

Related Questions