How can I clean up this code to be shorter? [dupli

2019-06-14 19:28发布

This question already has an answer here:

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?

标签: autoit
2条回答
劳资没心,怎么记你
2楼-- · 2019-06-14 19:36
For $i = 1 To 40

   $aItemsBySlot[$i] = GetItemBySlot(1, $i)

Next

As per Documentation - Intro - Arrays:

An Array is a variable containing a series of data elements. Each element in this variable can be accessed by an index number which relates to the position of the element within the Array - in AutoIt the first element of an Array is always element [0]. Arrays elements are stored in a defined order and can be sorted.

Example in GetItemBySlotMulti() (untestes, no error-checking):

Global $aItems

; Assign:
$aItems = GetItemBySlotMulti(1, 40)

; Retrieve single value (output item #1 to console):
ConsoleWrite($aItems[1] & @CRLF)

; Retrieve all values:
For $i = 1 To $aItems[0]

   ConsoleWrite($aItems[$i] & @CRLF)

Next

; Retrieve amount of items:
ConsoleWrite($aItems[0] & @CRLF)

; Re-assign a single value (re-assign item #1):
$aItems[1] = GetItemBySlot(1, 1)

; Function (used to assign example):
Func GetItemBySlotMulti(Const $iSlot, Const $iItems)
   Local $aItemsBySlot[$iItems +1]
         $aItemsBySlot[0] = $iItems

   For $i = 1 To $iItems

      $aItemsBySlot[$i] = GetItemBySlot($iSlot, $i)

   Next

   Return $aItemsBySlot
EndFunc

Related.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-06-14 19:54

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).

查看更多
登录 后发表回答