This one weird trick allows you to capture loop variables.

Paul Backus snarwin at gmail.com
Sun Oct 20 17:48:15 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
>
> How does it work? It works because opApply is passed a lambda 
> function generated by the compiler to implement the foreach 
> body.
>
> But because this is a *separate* function, when you close over 
> that lambda, the lambda's stack is independently allocated on 
> the heap for each loop iteration.

This is cute and all, but the correct solution is to fix the damn 
compiler. The fact that this is necessary in the first place is 
an embarrassment.


More information about the Digitalmars-d mailing list