如何检查变量是否已在 AutoHotkey 中赋值?

How to check if a variable has been assigned a value in AutoHotkey?

#Warn

WinActivate ahk_class %PrevActiveClass%

当运行执行上述代码时,解释器抛出:

我想检查PrevActiveClass是否被赋值,如果有,则运行WinActivate,如何在AutoHotkey中实现这个逻辑?

这是我通常用来检测空变量的方法

代码:

;#Warn

^r::
if(!PrevActiveClass){
    MsgBox not set yet
}
else{
    WinActivate ahk_class %PrevActiveClass%
}
return

^e::WinGetClass, PrevActiveClass, A ; Sets the variable to be the active window for testing

在 AHK 中,空变量被视为布尔值 false。因此,您可以在 if 语句中检查它以确定它是否包含任何内容。使用此方法的一个警告(尽管它不适用于您的用例)是如果您将布尔值 false 值分配给 var.

,它不会按预期工作

如果你真的想检查一个变量是否已经被设置,你可以通过比较它的地址(docs)和一个非存在变量:

var1 := ""      ;will return non-existent, this doesn't actually really create a variable
var2 := "hello" ;will return non-empty
var3 := "test"  ;now a variable actually gets created
var3 := ""      ;but here we set it to be empty, so it'll return empty
var4 := false   ;will return non-empty
;var5           ;will return non-existent


MsgBox, % (&Var1 = &NonExistentVar ? "Non-existent" : (Var1 = "" ? "Empty" : "Non-empty")) "`n"
        . (&Var2 = &NonExistentVar ? "Non-existent" : (Var2 = "" ? "Empty" : "Non-empty")) "`n"
        . (&Var3 = &NonExistentVar ? "Non-existent" : (Var3 = "" ? "Empty" : "Non-empty")) "`n"
        . (&Var4 = &NonExistentVar ? "Non-existent" : (Var4 = "" ? "Empty" : "Non-empty")) "`n"
        . (&Var5 = &NonExistentVar ? "Non-existent" : (Var5 = "" ? "Empty" : "Non-empty"))

但实际上,几乎总是(至少如果您设计得很好)您只需评估变量的布尔值就可以了,如其他答案所示。通过这种方式,您可以轻松地在 if 语句 if (var).

中检查变量的 existence
var1 := ""
var2 := "hello"
var3 := "0"
var4 := false
var5 := -1

MsgBox, % !!var1 "`n"
        . !!var2 "`n"
        . !!var3 "`n"
        . !!var4 "`n"
        . !!var5 "`n"

唯一需要注意的是 false ( 和 0false 是一个包含 0)), "" 和一个实际不存在的变量。


AHKv2 为此实现了自己的内置函数:
https://lexikos.github.io/v2/docs/commands/IsSet.htm

引自#Warn

Enables or disables warnings for specific conditions which may indicate an error, such as a typo or missing "global" declaration.

#Warn [WarningType, WarningMode]

WarningType

The type of warning to enable or disable. If omitted, it defaults to All.

UseUnsetLocal or UseUnsetGlobal: Warn when a variable is read without having previously been assigned a value or initialized with VarSetCapacity(). If the variable is intended to be empty, assign an empty string to suppress this warning.

This is split into separate warning types for locals and globals because it is more common to use a global variable without prior initialization, due to their persistent and script-wide nature. For this reason, some script authors may wish to enable this type of warning for locals but disable it for globals. [emphasis added]

#Warn
; y := "" ; This would suppress the warning.
x := y ; y hasn't been assigned a value.

在这种情况下,关闭 UseUnsetGlobal 的警告是安全的:

#Warn
#Warn UseUnsetGlobal, Off

WinActivate ahk_class %PrevActiveClass%