Closures and loop scope
w0rp
devw0rp at gmail.com
Tue Jun 4 12:45:29 PDT 2013
Huh, this is disappointing. I haven't used closures enough in D
to notice this issue, but I know of this kind of issue very well,
because it is a common annoyance in JavaScript. Newer,
non-cross-browsers versions of JavaScript get around this with
'let' instead of 'var,' which introduces block scope. So
something like this works as expected:
let arr = Array(5);
for (let i = 0; i < 5; ++i) {
arr[i] = function() { return i; }; // The scoped i is used
here.
}
let anotherArr = Array(5);
for (let i = 0; i < 5; ++i) {
anotherArr[i] = arr[i](); // Return a different i each time.
}
console.log(anotherArr); // 0, 1, 2, 3, 4, as expected
Is it possible for similar semantics to exist in D by default? I
imagine this is harder to implement.
More information about the Digitalmars-d
mailing list