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
    

Reply via email to