Metaprogramming and variable scope (again)

Hi there, I’m having some troubles understanding variable scoping in macros. Here is the simplest code to show my problems

macro foo(f) 
    quote
        x = 2
        $f
    end
end

function bar(y)
    @foo sum(x*i for i in 1:y)
end

If I run this code from the REPL I get ERROR: UndefVarError: y not defined. However, if I define y in the REPL, then everything works fine. It is possible to make the above example work as it should?

You are running into a hygiene issue, and need to esc variables and expressions that you don’t want to be renamed for macro hygiene:

julia> macro foo(f) 
           quote
               $(esc(:x)) = 2
               $(esc(f))
           end
       end
2 Likes

Steven is right. Alternatively, the entire expression can be escaped to get the “copy paste” behaviour that is often expected (although one should be aware of the potential pitfalls):

macro foo(f)
    ex = quote
        x = 2
        $f
    end
    esc(ex)
end

thanks, this solves my issue