AutoHotkey 中的一行 if-condition-assignment

One line if-condition-assignment in AutoHotkey

在JavaScript中,我们可以使用下面的一行代码:

const condition = true

let foo

condition && (foo = 'foo') //  one-liner

console.log(foo) // foo

我在 AHK 试过这个:

condition := true

condition && (foo := "foo")

MsgBox % foo

然而,解释器抛出:

我不得不将上面的代码更改为以下代码以提示“foo”:

condition := true

;  three lines
if (condition) {
  foo := "foo"
}

MsgBox % foo

如何在 AHK 中一行完成这种赋值?

我们可以使用 ternary operator (?:) 来实现这一点,与 JavaScript 不同,我们可以省略 AutoHotkey 中的丢失分支:

condition := true

condition ? foo := "foo"

MsgBox % foo

另外,引自0x464e

Note that you can only omit the losing branch if you're not trying to get the evaluation result of the whole ternary, e.g. var1 := TrueCondition ? "hello" does not work. The variable var1 doesn't get any value set to it.