It's very easy with "quote do":
import macros
proc my_enter(x: int): int =
echo "my_enter was called"
return x
proc my_exit(x: int) =
echo "my_exit was called"
macro take(args, body: untyped): untyped =
# Value of an argument
let varValue = args[1]
# Variable name
let varName = args[^1]
result = quote do:
# Private variable would be "private", so it wouldn't be redefined
var private = `varValue`
# We need to have a block to make sure varName is not redefined
block:
var `varName` = my_enter(private)
try:
`body`
finally:
my_exit(private)
take 3 as f:
echo f
take 6 as f:
echo f
- Python-like context managers and wizzardx
- Re: Python-like with, context managers, and the RAII pat... Tiberium
- Re: Python-like with, context managers, and the RAII... Arrrrrrrrr
- Re: Python-like with, context managers, and the ... pgmf
- Re: Python-like with, context managers, and ... wizzardx
- Re: Python-like with, context managers,... stisa
- Re: Python-like with, context manag... wizzardx
- Re: Python-like with, context m... Tiberium
- Re: Python-like with, context m... Udiknedormin
- Re: Python-like with, context m... Tiberium
- Re: Python-like with, context m... Udiknedormin
- Re: Python-like with, context m... Tiberium
- Re: Python-like with, context m... wizzardx
- Re: Python-like with, context m... Arrrrrrrrr
