As far as I could understand this Nim code
var arr = newSeq[proc()]()
for j in 0..<10:
let x : int = j + 1
let p = proc() = echo x
arr.add(p)
for p in arr:
p()
should be equivalent to the following Javascript code
var arr = []
for (let j=0; j<10; j++)
{
let x = j + 1
let p = () => console.log(x)
arr.push(p)
}
for(p of arr) p()
actually the Nim version always prints 10 instead of the whole sequence from 1 to 10.. I cannot understand how lambda capture works since the captured variable x should be local to the scope of the for loop and a new instance should be created for every iteration. Also, is there a way to capture variables by value? How could I fix the previous example to make it functionally equivalent to the Javascript one?This works:
var arr = newSeq[proc()]()
for j in 0..<10:
closureScope:
let x : int = j + 1
let p = proc() = echo x
arr.add(p)
for p in arr:
p()
See https://nim-lang.org/docs/manual.html#closures-creating-closures-in-loops
Thanks, I had missed that paragraph in the manual! So without the closureScope template the loop just generates one closure with the intances used in the last iteration and every proc that tries to make a capture actually captures that closure, is that correct?
Also, it is totally unrelated, but is there a specific reason why I cannot compile the generated Javascript source with the closure compiler?
It gives me an error because of an undeclared variable in a loop
nimcache/jpacrepo.js:1727: ERROR - variable property is undeclared
for (property in x_147603) {
simply replacing "property" with "var property" seems to fix the issue (the variable 'property' seems to be used only within the scope of the for loop, it's not used as a global variable, so this should be safe to do)