全局变量没有全局作用域 [英] Global variable does not have global scope
问题描述
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
运行代码,结果为:
"The global variable value is . The local variable value is asdf."
文档 指出:
变量范围和声明:局部变量除外在函数中,所有变量都是全局的;也就是说,它们的内容可能是由脚本的任何部分读取或更改.
Variable scope and declarations: With the exception of local variables in functions, all variables are global; that is, their contents may be read or altered by any part of the script.
为什么我的全局变量在函数内没有作用域?
Why does my global variable not have scope within the function?
推荐答案
全局变量的文档可以在这里找到:
https://autohotkey.com/docs/Functions.htm#Global
The documentation for global variables can be found here:
https://autohotkey.com/docs/Functions.htm#Global
全局变量
在函数内部引用现有的全局变量(或创建一个新的),在使用它之前将变量声明为全局变量.为了例子:
To refer to an existing global variable inside a function (or create a new one), declare the variable as global prior to using it. For example:
LogToFile(TextToLog)
{
global LogFileName
FileAppend, %TextToLog%`n, %LogFileName%
}
我认为 AHK 中的 global 概念与其他语言中的略有不同.使用 AHK,您可以创建一个变量并在多个热键和子例程中使用它,而无需将其声明为全局变量.
I believe the concept of global, with AHK, is a bit different than in other languages. With AHK you can create a variable and use it within multiple hotkeys, and subroutines, without declaring it as global.
Gv := 0
f1::SetTimer, Action, % (on:=!on) ? (1000) : ("Off")
Action:
Gv++
trayTip,, % Gv
Return
f2::Msgbox, % Gv
代码说明:
- F1 键切换计时器以运行子程序:
Action
每1000
ms. %
开始一个表达式.on:=!on
每次按下 F1 都会反转变量on
的二进制值.?:
一起称为三元运算符.- 当 on=1 延迟设置为
1000
ms 时;当 on=0 时,定时器关闭Off
.
- The F1 key toggles a timer to run the subroutine:
Action
every1000
ms. %
starts an expression.on:=!on
reverses the binary value of variableon
every time F1 is pressed.?:
together is called the ternary operator.- When on=1 delay is set to
1000
ms; when on=0 the timer is turnedOff
.
++
运算符将变量 Gv 加 1.
The ++
operator adds 1 to variable Gv.
这篇关于全局变量没有全局作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!