Search code examples
for-looplambdapass-by-referenceanonymous-functionnim-lang

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?


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.