I think you can do like this
```
macro wrap(expr)
:(global a=1;
r = (() -> $(esc(expr)))();
global a=0;
r)
end
@wrap (if a==1 return 3 else 0 end)
```
Erik Schnetter於 2014年12月19日星期五UTC+8上午11時41分39秒寫道:
>
> 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] <javascript:>>
> http://www.perimeterinstitute.ca/personal/eschnetter/
>