The global variable is not global.

supposedlyGlobalVariable := "blah" ARoutine() { localVariable := "asdf" MsgBox, The global variable value is %supposedlyGlobalVariable%. The local variable value is %localVariable%. } ^!X:: ;This assigns the hotkey CTRL + ALT + X to run the routine ARoutine() return 

Run the code and the result:

 "The global variable value is . The local variable value is asdf." 

The documentation states:

The scope of variables and declarations: With the exception of local variables in functions, all variables are global; that is, their contents can be read or modified by any part of the script.

Why does my global variable have no scope inside the function?

+6
source share
2 answers

The documentation on global variables can be found here:
https://autohotkey.com/docs/Functions.htm#Global

Global variables

To refer to an existing global variable inside a function (or create a new one), declare the variable as global before using it. For example:

 LogToFile(TextToLog) { global LogFileName FileAppend, %TextToLog%`n, %LogFileName% } 

I believe that the concept of the global, with AHK, is slightly different from the concept in other languages. With AHK, you can create a variable and use it in several hot keys and routines without declaring them global.

 Gv := 0 f1::SetTimer, Action, % (on:=!on) ? (1000) : ("Off") Action: Gv++ trayTip,, % Gv Return f2::Msgbox, % Gv 

Code Explanation:

  • The F1 key toggles the timer to start the routine: Action every 1000 ms.
  • % starts the expression.
  • on:=!on changes the binary value of the on variable each time F1 is pressed.
  • ?: together called the ternary operator.
  • When the value on = 1 is set to 1000 ms; when enabled = 0, the timer turns Off .

The ++ operator adds 1 to the Gv variable.

+9
source

P.Brian, it works when you do it. I know this does not explain why, but it could be your workaround.

 #Persistent GlobalVariable = "blah" RETURN ARoutine: { localVariable := "asdf" MsgBox, The global variable value is %GlobalVariable%. The local variable value is %localVariable%. } Return ^!X:: ;This assigns the hotkey CTRL + ALT + X to run the routine gosub, ARoutine return 
0
source

Source: https://habr.com/ru/post/913460/


All Articles