Search code examples
javascriptarraysvariablesautohotkeyspread-syntax

How to spread a variable in AutoHotkey?


In JavaScript, we use the spread operator to spread an array of items, e.g.

const arr = [1, 2, 3]

console.log(...arr) // 1 2 3

And I want to achieve a similar effect in AHK:

Position := [A_ScreenWidth / 2, A_ScreenHeight]

MouseMove Position ; 👈 how to spread it?

Solution

  • AFAIK, there's no spread syntax in AHK, but there are some alternatives:

    For big arrays you can use:

    position := [A_ScreenWidth / 2, A_ScreenHeight]
    Loop,% position.Count()
        MsgBox % position[A_Index] ; show a message box with the content of any value
    

    or

    position := [A_ScreenWidth / 2, A_ScreenHeight]
    For index, value in position
        MsgBox % value ; show a message box with the content of any value
    

    In your example, can be:

    position := [A_ScreenWidth / 2, A_ScreenHeight]
    MouseMove, position[1], position[2]
    

    This will move your mouse to the bottom middle of your screen.

    To avoid decimals, you may use Floor(), Round(), Ceil() functions for example, like:

    position := [ Floor( A_ScreenWidth / 2 ), Round( A_ScreenHeight ) ]
    Loop,% position.Count()
        MsgBox % position[A_Index] ; show a message box with the content of any value