Is there a way to have an iterator finalizer? It can be used to release allocated resources (close files, disconnect, etc) in case of break or if an exception is thrown.
Consider the following example:
iterator foo(): int =
var a = init()
while a.hasNext():
yield a.nextValue()
a.cleanup()
for i in foo():
discard # OK
for i in foo():
if i == 0:
break # Bad: cleanup() is not calledNice, thank you.
Updated example for the completeness:
iterator foo(): int =
var a = init()
try:
while a.hasNext():
yield a.nextValue()
finally:
a.cleanup()