Skip to content

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

Open
@PureFox48

Description

@PureFox48

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions