是否可以在不破坏代码的情况下将 `if ... in` 和 `{` 放在同一行?

Is it possible to keep `if ... in` and `{` on the same line without breaking the code?

;  not work
Var := "Var"

if Var in Foo,Bar,Baz {
  MsgBox statement 1
  MsgBox statement 2
} else {
  MsgBox statement 3
  MsgBox statement 4
}

;  not work
Var := "Var"

if (Var in Foo,Bar,Baz) {
  MsgBox statement 1
  MsgBox statement 2
} else {
  MsgBox statement 3
  MsgBox statement 4
}

;  works, but the brace positions are inconsistent,
;    is it possible to keep `if ... in` and `{`
;    on the same line without breaking the code?
Var := "Var"

if Var in Foo,Bar,Baz
{
  MsgBox statement 1
  MsgBox statement 2
} else {
  MsgBox statement 3
  MsgBox statement 4
}

if ... in(docs) 是遗留的,因此您不能将它括在括号内,因为那将表示一个表达式。不能将括号放在同一行只是 if ... in.

的限制

不幸的是,没有直接的现代替代品,所以 if ... in 无法满足您的要求。

但是,您可以放弃 if ... in 和旧语法并使用例如正则表达式匹配 shorthand 运算符 ~=(docs) 像这样:

Var := "Var"

if (Var ~= "Foo|Bar|Baz") {
  MsgBox, % "nope"
} else if (Var ~= "Foo|Var|Baz") {
  MsgBox, % "yup"
}

根据 user3419297 的评论进行编辑:

如果您不 anchor 正则表达式模式,它也会匹配子字符串。如果您知道存在匹配子字符串的风险,请务必添加 ^$ 锚点,例如像这样:

(Var ~= "^(Foo|Var|Baz)$")

也许:

Var := "Foo"
MsgBox % var = "Foo" ? "Statement 1"    ; if var  = foo
       : var = "Bar" ? "Statement 2"    ; if var  = bar
       : var = "Baz" ? "Statement 3"    ; if var  = baz
       :               "Statement 4"    ; if var != foo,bar and baz

或只是(与上面相同,但有 2 行):

Var := "Foo"
MsgBox % var = "Foo" ? "Statement 1" : var = "Bar" ? "Statement 2" : var = "Baz" ? "Statement 3" : "Statement 4"

这里有 autohotkey 中三元运算符的文档。