I read it from rosettacode:
var funcs: seq[proc(): int] = @[]
for i in 0..9:
let x = i
funcs.add(proc (): int = x * x)
for i in 0..8:
echo "func[", i, "]: ", funcs[i]()
but the output very odd
func[0]: 81
func[1]: 81
func[2]: 81
func[3]: 81
func[4]: 81
func[5]: 81
func[6]: 81
func[7]: 81
func[8]: 81
how to fix that?It changed in the last major release http://nim-lang.org/news.html#Z2016-01-18-version-0-13-0-released
var funcs: seq[proc(): int] = @[]
for i in 0..9:
(proc() =
let x = i
funcs.add(proc (): int = x * x))()
for i in 0..8:
echo "func[", i, "]: ", funcs[i]()
You can ease the pain using templates (Run It):
template loopClosure(body: untyped) =
block:
proc lc = body
lc()
[...]
for i in 0..9:
loopClosure:
let x = i
add funcs, proc: int = x * x
You can ease the pain using templates
thanks. good idea.