PDA

View Full Version : foreach missing element!


JustBreathe
06-24-2006, 12:42 PM
function onCreated()
{
temp.var = {1,2,3};
for ( temp.v: temp.var )
{
echo( temp.v );
if ( temp.v == 1 )
temp.var.remove( temp.v );
}
}


Output:

1
3


That is... When you remove an index within a for ( element: array ), the following element is skipped... That is, the index of the array isn't backed up by the amount of indexes deleted/removed.

Admins
06-24-2006, 01:46 PM
You are not supposed to modify the array of a for-each loop, it
would be too hard to detect insertion or removal of array members
and still run the for-each loop for each member. We should add
that to the wiki-docu though.

btw: firefox crashed two times when typing this reply, wondering why x-x

JustBreathe
06-24-2006, 02:44 PM
Custom Array's would solve a lot of these problems...


for ( element: array )

maps to:

while ( element = array.getNextIndex() )

// Array Class
publc function delete( index )
{
if ( index < this.curr_index )
this.curr_index --;

for ( i = 0; i < this.size(); i++)
if ( i > index )
this.element.(@ i ) = this.element.(@ i + 1);
}

public function size()
{
while ( this.element.(@temp.count) != false ) temp.count ++;
return temp.count;
}

public function getNextIndex()
{
this.curr_index ++;
if ( this.size() < this.curr_index )
return false;
return this[ this.curr_index ];
}


That would fix it... But that would require something like new TGraalArray();

NOTE: This would also have to remap array[ index ] to array.element.(@ index )

Admins
06-24-2006, 03:17 PM
It's not always that simple, e.g. it must be 'thread-safe', when you call sleep() inside the loop then it must still be working once the timeout occurs. That's why it just remembers the array variable and the index, most of the time that should be ok. If you need more control then you can use a normal for-loop I guess.