crayon
crayon copied to clipboard
Weird interaction with closures and foreach loops
This should print a, b, 2, c, 3, d
but instead it goes a, b, 1, ...
and then crashes with an out of range error
function main() {
things = ['a', 'b', 'c', 'd'];
for (thing : [0, 1].map((i) => { things[i]; })) {
print(thing);
}
for (i : [2, 3]) {
print(i);
print(thing[i]);
}
}
I just stumbled across this in my own code. Here's a slightly simpler example:
function main() {
list = [1];
closure = () => {
for (elem : list) {
print(elem); // 2
}
};
elem = 2;
closure();
}
I conjecture that what's happening is that during variable lookup in the body of a lambda, for-loop variable bindings are given lower precedence than capture bindings. Just a guess.