access foreach index counter for Iterate n times

mw mingwu at gmail.com
Sat May 21 01:01:40 UTC 2022


Not sure if this has been discussed before:

https://tour.dlang.org/tour/en/basics/foreach

```
foreach (i, e; [4, 5, 6]) {
     writeln(i, ":", e);
}
// 0:4 1:5 2:6
```

so what if I want the loop index counter when I want to loop n 
times with the .. syntax, I tried:

```
foreach (i, e; 5 .. 10) {
     writeln(i, ":", e);
}
```

right now when I tried it, got syntax error:

onlineapp.d(4): Error: found `..` when expecting `)`
onlineapp.d(4): Error: found `)` when expecting `;` following 
statement

Yes, there are a number of manual work-around, but I think the 
this 2nd foreach loop should be as valid as the 1st one on 
arrays, so the language behavior is more consistent.

Thoughts?


More information about the Digitalmars-d mailing list