wren icon indicating copy to clipboard operation
wren copied to clipboard

Should we document this aspect of for loop control variable behavior?

Open PureFox48 opened this issue 1 year ago • 0 comments

I was looking through the release notes for Go 1.21 when I came across LoopVarExperiment.

The first two examples are irrelevant to Wren as they're using parallel processing which, of course, we don't have.

However, the equivalent Wren code for the third example is:

var print123 = Fn.new {
    var prints = []
    for (i in 1..3) {
        prints.add(Fn.new { System.print(i) })
    }
    for (print in prints) print.call()
}

print123.call()

/*
1
2
3
*/

which (thankfully) prints 1, 2, 3 because Wren is effectively creating a new variable in each iteration of the loop and it is that variable which is captured by the closure.

However, this behavior is not obvious and anyone who is new to Wren but has experience in other languages which suffer from this problem might think that they have to do something like this to circumvent it:

var print123 = Fn.new {
    var prints = []
    for (i in 1..3) {
        var j = i  // create new variable
        prints.add(Fn.new { System.print(j) }) // capture new variable
    }
    for (print in prints) print.call()
}

I was wondering therefore whether we should document it somewhere? The most obvious place would be in the Control Flow - For statement - section. Perhaps something on the following lines as a separate paragraph at the end:

"Note that a fresh variable is created for each iteration of the loop and so, if a function in the body captures that variable, its value will not be affected by subsequent iterations."

Any thoughts or suggestions before I launch off on a PR for this?

PureFox48 avatar Aug 17 '23 11:08 PureFox48