You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
varprint123=Fn.new{varprints=[]for(iin1..3){varj=i// create new variableprints.add(Fn.new{System.print(j)})// capture new variable}for(printinprints)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?
The text was updated successfully, but these errors were encountered:
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:
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:
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?
The text was updated successfully, but these errors were encountered: