variablestry-catchautohotkeyahk2

How to check if a variable has been assigned a variable in AutoHotKey?


How might one check if a variable exists before using it? For example, you might have an Object that can contains 36 keys, one for each alphanumeric character, and you want to set another variable to the value of the key you selected.


Solution

  • This code could look like this:

    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
    

    This code would work, unless the key that was entered doesn't exist, in which case an error will be thrown. In order to avoid that situation, we can add turn myVar := myObject.%getInput.Input% into a Try statement. Now, our code will look like this:

    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
    

    Now, if the pressed key is not a key existing in myObject, then myVar will be set to an empty value. The catch statement is not required, but including it means that any future operations on myVar will have a value to operate on.

    You can find more information on Try-Catch statements on the AutoHotkey Docs.