try/finally does this. for an example, see the implementation of
`cd(::Function)` in Base.

(`@inbounds` doesn't return a value to force you to put it outside an
expression, not because it couldn't)

On Thu Dec 18 2014 at 10:41:38 PM Erik Schnetter <[email protected]>
wrote:

> I want to write a macro that performs certain actions before and after
> an expression, returning the value of the expression. Here is my first
> try:
>
> macro wrap(expr)
>     :(global a=1;
>       r = $(esc(expr));
>       global a=0;
>       r)
> end
>
> Obviously, setting the global variable `a` to 1 and 0 are just
> placeholder actions.
>
> This works for expressions, but doesn't work when `return` statements
> are involved.
>
> julia> @wrap 3
> 3
>
> julia> @wrap (if true return 3 else 0 end)
> ERROR: syntax: misplaced return statement
>
> This simpler case demonstrates the problem:
>
> julia> @wrap (return 3)
> => ERROR: syntax: misplaced return statement
>
> The problem goes away if I don't try to conserve the result into a
> variable `r`. However, I really need to do that. How?
>
> -erik
>
> PS: The macro `@inbounds` in Base has the same issue -- I assume this
> is the reason why it doesn't return a value.
>
> --
> Erik Schnetter <[email protected]>
> http://www.perimeterinstitute.ca/personal/eschnetter/
>

Reply via email to