[Issue 21929] delegates capture do not respect scoping

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue May 18 17:35:43 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=21929

Vladimir Panteleev <dlang-bugzilla at thecybershadow.net> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |dlang-bugzilla at thecybershad
                   |                            |ow.net
         Resolution|---                         |INVALID

--- Comment #1 from Vladimir Panteleev <dlang-bugzilla at thecybershadow.net> ---
In JavaScript:

---------------------------------------------------------------
var dgs = [];

for (var i = 0; i < 10; i++) {
        dgs.push(function() {
                console.log(i);
        });
}

dgs.push(function() {
        console.log("With cached variables");
});

for (var i = 0; i < 10; i++) {
        var index = i;
        dgs.push(function() {
                console.log(index);
        });
}

for (var dg of dgs) {
        dg();
}
---------------------------------------------------------------

Prints:

---------------------------------------------------------------
10
10
10
10
10
10
10
10
10
10
With cached variables
9
9
9
9
9
9
9
9
9
9
---------------------------------------------------------------

So, I don't think D's behavior is unexpected compared to other languages.

Note that if you change "var" to "let" in JS then it behaves closer as to what
you may expect.

At this point this is part of the language and is not a bug, so I don't think
the bugtracker is the proper place to post this.

The workaround in D is the same as in JavaScript (before "let"), pass the
mutable values to the lambda so that their current values become part of the
lambda's state (or create an outer lambda which does this).

--


More information about the Digitalmars-d-bugs mailing list