summary refs log tree commit diff stats
path: root/lib
diff options
context:
space:
mode:
authorAndreas Rumpf <rumpf_a@web.de>2016-07-04 10:41:48 +0200
committerGitHub <noreply@github.com>2016-07-04 10:41:48 +0200
commit5f9da6b2ae137feb762c149ed5a7e0eb0f23a17d (patch)
tree12a1341f6693ef956f68a059b60c4cf607660fe1 /lib
parentec63f8c3e4bb0d9439e7613b281bccb33ce1e575 (diff)
parente61cfea78b9ebb8df734c7b9d15d81b50ce76613 (diff)
downloadNim-5f9da6b2ae137feb762c149ed5a7e0eb0f23a17d.tar.gz
Merge pull request #4420 from yglukhov/closure-scope
Added closureScope template
Diffstat (limited to 'lib')
-rw-r--r--lib/system.nim21
1 files changed, 21 insertions, 0 deletions
diff --git a/lib/system.nim b/lib/system.nim
index 5a84f4a52..6a4265e5a 100644
--- a/lib/system.nim
+++ b/lib/system.nim
@@ -3633,6 +3633,27 @@ proc `==` *(x, y: cstring): bool {.magic: "EqCString", noSideEffect,
   elif x.isNil or y.isNil: result = false
   else: result = strcmp(x, y) == 0
 
+template closureScope*(body: untyped): stmt =
+  ## Useful when creating a closure in a loop to capture local loop variables by
+  ## their current iteration values. Example:
+  ##
+  ## .. code-block:: nim
+  ##   var myClosure : proc()
+  ##   # without closureScope:
+  ##   for i in 0 .. 5:
+  ##     let j = i
+  ##     if j == 3:
+  ##       myClosure = proc() = echo j
+  ##   myClosure() # outputs 5. `j` is changed after closure creation
+  ##   # with closureScope:
+  ##   for i in 0 .. 5:
+  ##     closureScope: # Everything in this scope is locked after closure creation
+  ##       let j = i
+  ##       if j == 3:
+  ##         myClosure = proc() = echo j
+  ##   myClosure() # outputs 3
+  (proc() = body)()
+
 {.pop.} #{.push warning[GcMem]: off, warning[Uninit]: off.}
 
 when defined(nimconfig):