Created
August 5, 2023 14:55
-
-
Save MattAlp/ca24060733e1142ac4823179d69cedf9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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