D isn't the only language with janky closure semantics
H. S. Teoh
hsteoh at qfbox.info
Fri Aug 29 23:17:23 UTC 2025
On Fri, Aug 29, 2025 at 10:51:10PM +0000, Steven Schveighoffer via Digitalmars-d wrote:
> On Friday, 29 August 2025 at 22:28:17 UTC, H. S. Teoh wrote:
> > Now, JS is certainly not a model language to follow, but it's
> > interesting how it shares with D the same issue over closures
> > involving loop variables.
> >
> > I guess that means we're not alone. :-P Even though this situation
> > is definitely not ideal.
>
> Oh yeah, JS has similar behavior. You get the desired behavior by
> using `let` at the variable declaration. Otherwise, it becomes a
> regular declaration (one instance per function).
>
> I think your original code will work as you want with:
>
> ```js
> for (let button of buttons) {
> ```
Oooh yes, that *is* exactly what I was looking for. I already got
bitten before by for(... of) without `let`... still haven't learned my
lesson, it seems.
> Would be nice to have a similar trick for D...
Sneaky syntax proposal:
```d
void delegate()[] dgs;
foreach (scope i; 0 .. 100) { // N.B. `scope`
dgs ~= () {
writefln("%d", i); // <-- closes over independent instance of `i`
};
}
```
;-)
T
--
Give a man a fish, and he eats once. Teach a man to fish, and he will sit forever.
More information about the Digitalmars-d
mailing list