access foreach index counter for Iterate n times

Adam D Ruppe destructionator at gmail.com
Sat May 21 15:23:08 UTC 2022


On Saturday, 21 May 2022 at 15:06:31 UTC, mw wrote:
>> It isn't a loop counter. It is an index back into the original 
>> source. Consider:
>
> 1) First, why not 0 then 4? Since dchar is 32 bits.

It is an index back into the *original source* given to foreach.

I gave it a char[], not a dchar[]. So it is counting chars in 
that original char[].


If you do:

auto thing = whatever_you_loop_over;
foreach(index, item; thing) {
     then
       stuff_before_item == thing[0 .. index];
}


> Explanations?

The index there is the index into a dstring, which is stored 
differently.

> If it's "loop counter", isn't the behavior more consistent?

Also see `foreach_reverse` where it counts backwards because it 
is an index into the original array, not a counter.


More information about the Digitalmars-d mailing list