Skip to content

Instantly share code, notes, and snippets.

@MattAlp
Created August 5, 2023 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattAlp/ca24060733e1142ac4823179d69cedf9 to your computer and use it in GitHub Desktop.
Save MattAlp/ca24060733e1142ac4823179d69cedf9 to your computer and use it in GitHub Desktop.
import macros
macro namedFor(label: string, counter: string, loop_range: untyped, body: untyped): untyped =
result = newStmtList()
let
loopStmt = newTree(nnkForStmt, newIdentNode(counter.strVal), loop_range, body)
labelBlock = newTree(nnkBlockStmt, newIdentNode(label.strVal), loopStmt)
result.add(labelBlock)
macro namedWhile(label: string, condition: untyped, body: untyped): untyped =
result = newStmtList()
let
loopStmt = newTree(nnkWhileStmt, condition, body)
labelBlock = newTree(nnkBlockStmt, newIdentNode(label.strVal), loopStmt)
result.add(labelBlock)
# Usage
# Inspired by the convenient feature from Zig and my dislike of having the block statement and actual loop on different levels
var i = 0
namedFor("outerLoop", "i", 0..<10):
var j = 0
namedWhile("innerLoop", j < 10):
if i + j > 10:
echo "Breaking from outerLoop"
break outerLoop
echo "i: ", i, ", j: ", j
inc j
echo "After loops"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment