全局变量没有全局范围 [英] 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."
文档指出:
变量范围和声明:局部变量除外 在函数中,所有变量都是全局变量;也就是说,它们的内容可能是 通过脚本的 any 部分进行读取或更改.
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的全球概念与其他语言有所不同.使用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次. -
%
开始一个表达式.
每次按下 F1 时, -
on:=!on
都会反转变量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
.
++
运算符将1加到变量Gv.
The ++
operator adds 1 to variable Gv.
这篇关于全局变量没有全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!