How do I build a dynamic array and loop through it in AutoIt?

12,195

You can use UDF function _ArrayAdd for this purpose. For example,

#include <Array.au3>
Local $arr = []      ; NOTE this creates an array of size 1 with an empty string
_ArrayAdd($arr, 'lorem')
_ArrayAdd($arr, 'ipsum')

For $i = 1 To UBound($arr) - 1
    ConsoleWrite('arr[' & $i & '] == ' & $arr[$i] & @CRLF)
Next

OR you can use .NET class ArrayList. That is more flexible:

Local $arr = ObjCreate('System.Collections.ArrayList')
$arr.Add('lorem')
$arr.Add('ipsum')
$arr.Add('dolor')

ConsoleWrite("Contains 'dolor'? " & $arr.Contains('dolor') & @CRLF)

$arr.Sort()
For $i = 0 To $arr.Count - 1
    ConsoleWrite('arr[' & $i & '] == ' & $arr.Item($i) & @CRLF)
Next
Share:
12,195
Cesar Bielich
Author by

Cesar Bielich

By Day: Sys Admin/Coder/Problem Solver By Night: Coder/Coder/Coder + Mt. Dew...

Updated on August 02, 2022

Comments

  • Cesar Bielich
    Cesar Bielich over 1 year

    I was reading the official AutoIt Array Parameters, and from what I can tell you have to tell AutoIt how many elements your array has before you can even create it. Since my array will be dynamic according to what the user selects in my interface then I am in need of something like this.

    From their page:

    But say you don't know the size of the array upfront, because it may come in a variable size when created dynamically.

    Local $iMax
    
    Local $data="Element 1|Element 2|Element 3"
    
    ; The string in data will be split into an array everywhere | is encountered
    Local $arr = StringSplit($data, "|")
    
    If IsArray($arr) Then
         $iMax = UBound($arr); get array size
    
         ConsoleWrite("Items in the array: " & $iMax & @LF)
    
         For $i = 0 to $iMax - 1; subtract 1 from size to prevent an out of bounds error
         ConsoleWrite($arr[$i] & @LF)
         Next
    EndIf
    

    I have set up an if statement to go through the users selections and build the array first:

    If GUICtrlRead($Box1) = $GUI_CHECKED Then
       $data = "one|two|three"
    EndIf
    If GUICtrlRead($Box2) = $GUI_CHECKED Then
       $data = "four|five|six"
    EndIf
    If GUICtrlRead($Box3) = $GUI_CHECKED Then
       $data = "seven|eight|nine"
    EndIf
    

    If the user selected all three boxes I would need something like:

    $data = one|two|three|four|five|six|seven|eight|nine
    

    Then at this point I can pass these elements into the example above to loop through all my elements.

    How can I build the array through multiple if statements and come out with one large array?