Silly question about lists
BlitzMax Forums/BlitzMax Beginners Area/Silly question about lists
| ||
Hi, I have a list of MyType. When I'm going through the list I add more to the list. How does it know to ignore these additions and just process the original list? Obviously the next time I process the list it does them all including the additions. Jim |
| ||
How does it know to ignore these additions and just process the original list? It doesn't. When it gets to the end of the list, it will stop iterating through it. Here's an example : SuperStrict Framework brl.standardio Import brl.linkedlist Local list:TList = New TList list.AddLast("Hello") list.AddLast("World") Local i:Int = 0 For Local entry:String = EachIn list Print entry If i < 10 Then list.AddLast(String(i)) End If i:+ 1 Next You'll see that the list populates with 10 numbers, outputting the values as it goes. Now, comment out the line which adds "World" to the list and run it again. After it processes the first (and only) entry in the For, it has decided already that there are no more entries in the list, and so the enumerator's HasNext() will return False, thereby finishing the iteration. In the original version we are appending to the list before the enumerator has reached the end, so it never finds the end of the list until we stop appending to it. |
| ||
Its your myType list, so add a type global variable for the "original" last entry. Compare inside, (just before next), your eachin list, and pop out of list. (or don't if you don't want to.) |
| ||
Thanks guys, understood! Jim |
| ||
Mutating a collection as you roll over it is one of those things that's generally agreed to be a bad idea... while it's possible to determine what actually happens (as in Brucey's example), most compilers/languages will warn you that this sort of thing could be inconsistent and leave your collection in an unpredictable state. Whether checks are performed at the start or end of the loop, whether the enumerator actually runs or gets optimized out, etc., is usually treated as unknown-and-unknowable. A much safer, simpler (and in many languages faster) option would be to use a temporary second list for your generated data, and append it to the original after the loop is done. |