如何在 AutoHotkey 的热键中声明局部变量?

Ste*_*ica 3 scope autohotkey local-variables

TL:博士;我不能热键里面变量声明为局部的,其手段tempindex全局访问。

我最近发现局部变量不能从热键中声明为局部变量,也不能在for-loop中用作参数。

^j::
   local temp = Hello, world!  ; Error: This line does not contain a recognized action
Return

SampleFunction() {
   for local temp in myArray {  ; Error: Variable name contains an illegal character
      ; do stuff
   }
}
Run Code Online (Sandbox Code Playgroud)

这成为#warn启用的问题。除非我记得为每个 for 循环使用唯一的变量名,否则我会遇到以下错误:

警告:此局部变量与全局变量同名。(具体:索引)

例如:

#warn

^j::
   index = 42  ; This *index* variable is global
Return

UnrelatedFunction() {
   for index in myArray {  ; This *index* variable is local
      MsgBox % myArray[index] 
   }
}
Run Code Online (Sandbox Code Playgroud)

特别是在使用导入时,这会成为一个问题,因为我自己脚本中的变量经常与我导入脚本中的变量发生冲突。

理想情况下,我可以在任何 for 循环之前放置一个本地声明,但如前所述,我无法在热键中执行此操作。

是否可以从热键中将变量声明为本地变量?

Jim*_*m U 5

我用函数实现了我的热键。除非声明,否则函数内的变量默认具有局部作用域global

F1::alpha(10,10)
F2::alpha(20,30)
F3::beta()


alpha(x,y)
{
   myvar := x*2 + y
}

beta()
{
   myvar := 47
}
Run Code Online (Sandbox Code Playgroud)

  • 从 https://autohotkey.com/docs/Functions.htm#lib,策略是在包含它的文件之后命名函数 - 这可以防止(在某种程度上)命名空间冲突。当然,这只是重新暴露了 OP 正在谈论的命名空间问题,只是使用函数名而不是变量名:) (2认同)