This one weird trick allows you to capture loop variables.

Dukc ajieskola at gmail.com
Wed Oct 30 07:50:18 UTC 2024


On Sunday, 20 October 2024 at 02:14:14 UTC, Steven Schveighoffer 
wrote:
> I thought of this when someone asked the age-old question about 
> [closures not capturing loop 
> variables](https://issues.dlang.org/show_bug.cgi?id=2043).
>
> https://gist.github.com/schveiguy/b6b037bdfe74997743de81f8d3f4b92b
>

For the most part, I prefer Timon's solution in the Bugzilla 
issue. For this particular example, it would be

```D
void main()
{   import std.stdio;
     void delegate()[] dgs;

     foreach(i; [1, 2, 3, 4])
     {   dgs ~= (x => () => writeln(x))(i);
     }
     foreach(d; dgs) d(); // 1, 2, 3, 4
}
```

I prefer this trick mostly because it also lets you to catch 
other things than just the element being iterated over.


More information about the Digitalmars-d mailing list