Hi, it's the weekend :)
Recently, I found that in python, we can break from the nested loop by using the for-else statement like this.
for i in range(5):
for j in range(5):
if i == j and j == 2:
break
else: # here we write something when the inner loop did not end with the break
continue
break # if the inner loop exited with the break, just break again
I think this is pretty good syntax, and I personally hope Nim will allow this syntax.
Nim has a similar function with named blocks:
block outer:
for i in 0..5:
for j in 0..5:
if i == j and j == 2:
break outer
Personally I'd like to see a way to name a for loop as well, to avoid the extra nesting
That I would like as well, also because named loops communicate stronger intent.
Thankfully the ForloopStmt macro exists which means we already have this!
import std/[macros, genasts]
macro `as`*(forLoop: ForLoopStmt): untyped =
let name = forLoop[^2][^1]
result = forLoop.copyNimTree
result[^2] = result[^2][^2]
result = newBlockStmt(name, result)
echo result.repr
for i in 0..5 as outer:
for j in 0..5:
if i == j and j == 2:
break outer
echo i , " ", j