For Loop through list, starting at the End of the List <SOLVED (KINDA)>

comport9

  • Posts: 51
Can you start at the end of a list with a For Loop? Reason being is I want to remove items from the list while iterating over it. If I don't start at the end, the list won't be properly iterated over.

« Last Edit: December 27, 2012, 04:29:27 pm by comport9 »

Hectate

  • *
  • Posts: 4643
I'm trying to follow what you're attempting to accomplish here. You want to loop over a list of items, occasionally removing them. If an item is removed you're concerned that now that the list has changed that the current iteration will not be accurate anymore?

Perhaps if you merely stopped the iteration and then just restarted it if you modified the list? You'd still be working from the beginning instead of the end but you'd have a "complete" list every time...

Otherwise, if you really want to work from the end of the list you have a couple of options (this is assuming you're in Stencyl 2.x and are thus needing AS3 code).

First, lists are AS3 Arrays, and thus can be modified using the Array's functions. One in particular that could be of use to you is the "reverse" function which does as it says. Reference the following link: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#reverse()
Code: [Select]
MyList.reverse();
Obviously if you want to keep the list in a particular order you'd need to re-reverse it at some point.

The second more complex way of doing this might be to 1. Get the number of items in the list, 2. perform a loop over the list starting with the highest number index and counting backward (using math to determine where you are each iteration).
:
:
Patience is a Virtue,
But Haste is my Life.
Proud member of the League of Idiotic Stencylers; doing things in Stencyl that probably shouldn't be done.

comport9

  • Posts: 51
You're correct in that I'm worried that changing the size of the list while iterating over it will cause items to be skipped. However, simply reversing the list doesn't solve that problem.

As Stencyl doesn't seem to have this as a feature, I simply created a temp list, removed items from that list, and then set the original list to the temp one.

While this works in this case, I can see other cases where being able to loop backwards would be important.

rob1221

  • *
  • Posts: 9473
Here's how you can loop through a list backwards.

comport9

  • Posts: 51
Ok. Yeah that should work. A bit convoluted though. ;)

Edit: Except, I need to do it for each actor on the screen. Is there a variable stored with the number of actors on the screen?

« Last Edit: December 27, 2012, 07:51:17 pm by comport9 »

rob1221

  • *
  • Posts: 9473
There's a (flash only) block for looping through all the actors on screen found under Scene > Actor I think.