Search code examples
autoit

How can I clean up this code to be shorter?


I'm using AutoIt:

$1 = GetItemBySlot(1, 1) 
$2 = GetItemBySlot(1, 2) 
$3 = GetItemBySlot(1, 3) 
$4 = GetItemBySlot(1, 4)  
$5 = GetItemBySlot(1, 5) 

The code repeats for 40 lines. How can I shorten it?


Solution

  • You could shorten this by using Assign() and Eval().

    For $i = 1 To 5
        Assign($i, GetItemBySlot(1, $i))
    Next
    

    That would be 3 lines instead of n lines. During runtime this will be expanded to:

    Assign(1, GetItemBySlot(1, 1))
    Assign(2, GetItemBySlot(1, 2))
    Assign(3, GetItemBySlot(1, 3))
    Assign(4, GetItemBySlot(1, 4))
    Assign(5, GetItemBySlot(1, 5))
    

    To get the data of those variables you need to use the Eval function. So

    For $i = 1 To 5
        Eval($i)
    Next
    

    returns the value of GetItemBySlot(1, $i).