如何检查AutoHotKey中的变量是否已被赋值?

问题描述 投票:0回答:1

在使用变量之前如何检查它是否存在?例如,您可能有一个包含 36 个键的对象,每个键对应一个字母数字字符,并且您希望将另一个变量设置为您选择的键的值。

variables try-catch autohotkey ahk2
1个回答
0
投票

此代码可能如下所示:

myObject := {} ; Create myObject

; Some other code here, possibly that adds key-value pairs to the Object

getInput := InputHook("L1") ; Create an InputHook to intercept one character
getInput.Start() ; Start the InputHook
getInput.Wait() ; Wait for a character input

myVar := myObject.%getInput.Input% ; Set myVar to the pressed key in myObject

此代码将起作用,除非输入的密钥不存在,在这种情况下将引发错误。 为了避免这种情况,我们可以将turn

myVar := myObject.%getInput.Input%
添加到
Try
语句中。现在,我们的代码将如下所示:

myObject := {} ; Create myObject

; Some other code here, possibly that adds key-value pairs to the Object

getInput := InputHook("L1") ; Create an InputHook to intercept one character
getInput.Start() ; Start the InputHook
getInput.Wait() ; Wait for a character input

Try myVar := myObject.%getInput.Input% ; Set myVar to the pressed key in myObject
Catch
    myVar := "" ; If pressed key in myObject doesn't exist, set myVar to empty value

现在,如果按下的键不是

myObject
中存在的键,则
myVar
将被设置为空值。
catch
语句不是必需的,但包含它意味着未来对
myVar
的任何操作都将具有可操作的值。

您可以在

AutoHotkey Docs
上找到有关 Try-Catch 语句的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.