https://issues.dlang.org/show_bug.cgi?id=21929
Vladimir Panteleev <[email protected]> changed: What |Removed |Added ---------------------------------------------------------------------------- Status|NEW |RESOLVED CC| |dlang-bugzilla@thecybershad | |ow.net Resolution|--- |INVALID --- Comment #1 from Vladimir Panteleev <[email protected]> --- 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). --
