crayon icon indicating copy to clipboard operation
crayon copied to clipboard

Weird interaction with closures and foreach loops

Open blakeohare opened this issue 5 years ago • 1 comments

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]);
	}
}

blakeohare avatar May 05 '19 21:05 blakeohare

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.

jonathansharman avatar Jan 21 '21 23:01 jonathansharman