summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorYuriy Glukhov <yutiy.glukhov@gmail.com>2016-06-27 17:44:05 +0300
committerYuriy Glukhov <yutiy.glukhov@gmail.com>2016-06-27 17:44:05 +0300
commitdef3e015c7a8c82430fff20994b75b233c0c423b (patch)
tree208d9ccc02be740ec8cc667c7eb8d27d2f2f7a25
parent38de553b86fd5f42c726da9bceb6828fb835eff5 (diff)
downloadNim-def3e015c7a8c82430fff20994b75b233c0c423b.tar.gz
Added closureScope template
-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):