Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Per-iteration variable in Nim?

var functions: seq[proc(): int] = @[]
functions.add(proc(): int = 233)
for i in 1 .. 5:
  functions.add(proc(): int = i)

for i in 1 .. 5:
  echo functions[i]()

output

5
5
5
5
5

Seems like Nim stores free variable i in these anonymous functions by reference instead of values just like Python, Ruby and Groovy. How can I get its value instead of reference?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the capture macro, see the docs in std/sugar

import std/sugar
var functions: seq[proc(): int] = @[]
for i in 1 .. 5:
  capture i:
    functions.add(proc(): int = i)

for fn in functions:
  echo fn()

There’s also captureScope in system (system module is always implicitly imported), but the docs suggest using capture from std/sugar.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading