是否可以在 Autohotkey 2 中指定要从 onEvent 调用的匿名函数?

Is it possible to specify an anonymous function to be called from onEvent in Autohotkey 2?

我想知道我是否可以在 Autohotkey V2 中指定要使用 onEvent 调用的匿名函数。

以下不起作用,脚本试图概述我试图实现的目标:

g := guiCreate()

txt := g.add('text', 'w200 r1')
txt.text := 'Hello!'

g.onEvent('close', (*) => function() {
  msgBox('Going to exit application')
  exitApp()
})

g.show()

胖箭头函数(() => expr)"evaluates the sub-expression expr and returns the result."(Source)

文档的下一部分指出:

Commas may be used to write multiple sub-expressions on a single line. This is most commonly used to group together multiple assignments or function calls. For example: x:=1, y+=2, ++index, MyFunc(). Such statements are executed in order from left to right.


这些变体似乎有效(我使用的是 v2.0-a108):

g.onEvent('close', (*) => (
  msgBox('Going to exit application')
  exitApp()
))

g.onEvent('close', (*) => (
  msgBox('Going to exit application'),
  exitApp()
))

g.onEvent('close', (*) => (msgBox('Going to exit application') exitApp()))

g.onEvent('close', (*) => (msgBox('Going to exit application'), exitApp()))

msgBox()exitApp() 之间的逗号似乎在多行和单行表达式中都是可选的。我认为没有逗号的多行表达式更清晰,而带有逗号的单行表达式更具可读性。

尽管如果您有更复杂的子表达式,则需要使用一些逗号。例如,如果第三行没有逗号,下面的代码将无法运行:

g.onEvent('close', (*) => (
  msgBox('Going to exit application')
  foo := 1 + 2,
  msgBox(foo)
  exitApp()
))

(或者,您可以写成 (foo := 1 + 2),并且不需要逗号。)

我不知道包含或省略逗号是否有其他影响。另见:comma performance.


您还可以将子表达式与 &&|| 结合起来。在下面的例子中,exitApp() 不会被调用,因为 1 > 2false。请注意,表达式两边的括号不是必需的:

g.onEvent('close', (*) => msgBox('Going to exit application') && 1 > 2 && exitApp())