Sign in to follow this  
Followers 0
therks

Foreach()

2 posts in this topic

#1 ·  Posted (edited)

If any of you have used PHP much, then you probably know about the Foreach construct, just in case you don't, it works pretty much like this:

$veggies = array('peas', 'corn', 'carrots');

foreach ($veggies as $key => $value) {
 echo "Index #" . $key . " = " . $value . "\n";
}

This would output:

Index #0 = peas
Index #1 = corn
Index #2 = carrots

Now, back to AutoIt. I'm trying to recreate this function just for my own ease of use. I'm not worried about multidimensional arrays just yet, 1 dimension is fine for my purposes so far. But I can't quite get it to work the way I want.

The way I wanted it to work was something like this:

Dim $myarray = StringSplit('carrots peas corn', ' ');

While Foreach($myarray, $key, $value)
 MsgBox(0, '', $key & ' = ' & $value);
WEnd

But the best I can work out, I need to first declare the $key and $value variables, because I can't get the Function to increment the array position and repeat itself without modifying an outside variable. Here's the function I have now:

Func _Foreach($aArray, ByRef $iIndex, ByRef $sValue)
    If IsArray($aArray) Then
  Local $iLen = UBound($aArray, 1);

  If $iIndex = $iLen Then
    Return 0;
  Else
    $sValue = $aArray[$iIndex];
    $iIndex = $iIndex + 1;
    Return 1;
  EndIf
    Else
  SetError(1);
  Return 0;
    EndIf
EndFunc

And the method for using it:

Dim $myarray = StringSplit('carrots peas corn', ' ');

Dim $count, $value;
While Foreach($myarray, $key, $value)
 MsgBox(0, '', $key & ' = ' & $value);
WEnd

And the problem with this, is that when it returns the $key, it's always 1 more than the actual current $value, ie: 1 = carrots, instead of 0 = carrots.

Obviously, the function works now, it works fine, it does what it's supposed to. I'd just really like if I didn't have to declare my variables first, and since I'm fairly new to AutoIt, I figured I would post it here and ask if anyone knew of a way to make this work the way I like.

Thanks for reading!

Edited by Saunders

Share this post


Link to post
Share on other sites



Don't use ByRef. ByRef REQUIRES that the variable be a variable not a literal string or number. Also, you should use ByRef for the array. Passing array's by value rather than by reference is a huge memory eater and performance bottleneck.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0