`if` 语句中的未定义变量

Undefined variables in `if` statement

这将按预期工作:

a := "111"
b := "222"

if (a != "aaa" and b != "bbb")
    MsgBox, Yes

但如果其中一个变量未定义,也会显示 "Yes" 消息

; a := "111" ; Commented line
b := "222"

if (a != "aaa" and b != "bbb")
    MsgBox, Yes ; Since var "a" is not defined, I don't want this message box

以下是我的修复方法:

; a := "111"
b := "222"

if ((a and b) and (a != "aaa" and b != "bbb"))
    MsgBox, Yes

但从我的角度来看,它看起来很糟糕。有没有更正确的方法?

因为 and 是可交换的,你可以不用括号:

if a and b and a != "aaa" and b != "bbb"

替代解决方案

将您的变量初始化为您正在测试的值 (aaa),这样如果您的实现代码不改变它们,您将获得所需的结果:

a=aaa
b=bbb

... do some stuff ...

global a,b
if a != "aaa" and b != "bbb"
    MsgBox, Yes

解释

aundefined 时,您似乎希望 undefined != "aaa" 以某种方式求值为 false。这等同于说您希望 undefined == "aaa" 以某种方式计算为 true。你的逻辑太复杂了。

这是您逻辑的状态 table:

                Actual  Desired T1      T2
a       b       MsgBox  MsgBox  a!=aaa  b!=bbb  T1 and T2
-----   ------  ------  ------- ------  ------  -----
undef   undef   Yes     no      true    true    true 
undef   bbb     no      no      true    false   false
undef   222     Yes     no      true    true    true    The example you didn't want
aaa     undef   no      no      false   true    false  
aaa     bbb     no      no      false   false   false
aaa     222     no      no      false   true    false
111     undef   Yes     no      true    true    true
111     bbb     no      no      true    false   false
111     222     Yes     Yes     true    true    true    Only one you want

Actual MsgBox 列显示消息框何时出现在您的原始代码中。 Desired MsgBox=是的,这就是您想要发生的事情。 T1T2 是您的条件的部分计算。 T1 and T2 是您条件的最终值。

最后一行显示了您希望 MsgBox 出现的唯一状态;当 a 不等于 aaa 也不等于 undefined AND b 不等于 bbb 也不等于 undefined.

所以我们可以简化逻辑,将a初始化为"aaa",将b初始化为"bbb"。实际上,我们通过使两个值("aaa" 和 undefined)相等,将每个变量的两个条件合并为一个条件。

我希望这是有道理的