Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
PureFox48 opened this issue Aug 17, 2023 · 0 comments · May be fixed by #1177
Open

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

PureFox48 opened this issue Aug 17, 2023 · 0 comments · May be fixed by #1177

Comments

@PureFox48
Copy link
Contributor

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant