I'm trying to automate a specific kind of try... except... finally.
Let's take this example:
try:
# some code to try
except X as e:
# do something
except Y as e:
# do something else
except Z as e:
# do something different
finally:
# code to execute nomatterwhat
Since the central part is quite repetitive, I want to create (preferably) a template that takes the "try" code and the "finally" code, to make things look a bit better. So that I could for example write something like (which would be translated to the code above):
tryDoingThis:
# code
andInTheEnd:
# code
I know templates can take a last untyped param. But in this case I would need two of them.
Any ideas?
You can do something like this:
template doStuff(first, second: untyped): untyped =
echo "doing first!"
first
echo "doing second!"
second
doStuff:
echo "in first!"
do:
echo "in second!"
Wow! Really?!
I hadn't even thought of it.
I'll try it after lunch and will let you know.
It sure looks fine. Let's see...
Thanks a lot! :)
OK... so I couldn't wait to test it, so I did.
Works beautifully! Yay!
Thanks A LOT.
This also works in 1.4.4:
template doStuffImpl(first, second: untyped): untyped =
echo "doing first!"
first
echo "doing second!"
second
import macros
macro doStuff(first, second: untyped): untyped =
result = getAst(doStuffImpl(first, second[0]))
doStuff:
echo "in first!"
finally:
echo "in second!"
Specifically this functionality for finally was only added in 1.4.4, it's been around for longer for except, elif, of, else, do etc.
block cannot be used directly for this, no. do is a bit of a special thing. But you can quite easily write a multi body macro using blocks as well. Something like the following:
import macros
macro multiMacro(blocks: untyped): untyped =
result = newStmtList()
template first(body: untyped): untyped =
echo "now first!"
body
template second(body: untyped): untyped =
echo "now second!"
body
let blk0 = blocks[0]
let blk1 = blocks[1]
expectKind(blk0, nnkBlockStmt)
expectKind(blk1, nnkBlockStmt)
result.add quote do:
first(`blk0`)
second(`blk1`)
multiMacro:
block:
echo "hello 1"
block:
echo "hello 2"
At some point there was talk about deprecating the do notation and @krux02 worked on a multi macro helper to do something like this. But in the ende it was decided to just keep it, iirc.
Uh, why are such things introduced in a point release?
Because it was a bugfix. It always was supposed to work.