# Metaprogramming and variable scope (again)

**URL:** <https://discourse.julialang.org/t/metaprogramming-and-variable-scope-again/49248>\
**Category:** New to Julia\
**Tags:** metaprogramming\
**Created:** [October 29, 2020, 4:49pm UTC](https://discourse.julialang.org/t/metaprogramming-and-variable-scope-again/49248 "2020-10-29T16:49:16Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![benkj](https://avatars.discourse-cdn.com/v4/letter/b/848f3c/32.png) [@benkj](https://discourse.julialang.org/u/benkj)\
**Post date:** [October 29, 2020, 4:49pm UTC](https://discourse.julialang.org/t/metaprogramming-and-variable-scope-again/49248/1 "2020-10-29T16:49:17Z")

</div>

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

```julia
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?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [October 29, 2020, 5:06pm UTC](https://discourse.julialang.org/t/metaprogramming-and-variable-scope-again/49248/2 "2020-10-29T17:06:06Z")

</div>

You are running into a [hygiene](https://docs.julialang.org/en/v1/manual/metaprogramming/#Hygiene) issue, and need to `esc` variables and expressions that you don’t want to be renamed for macro hygiene:

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

```

---

<div class="post-metadata">

**Author:** ![christopher-dG](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/christopher-dg/32/7387_2.png) [@christopher-dG](https://discourse.julialang.org/u/christopher-dG)\
**Post date:** [October 29, 2020, 5:26pm UTC](https://discourse.julialang.org/t/metaprogramming-and-variable-scope-again/49248/3 "2020-10-29T17:26:16Z")

</div>

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):

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

```

---

<div class="post-metadata">

**Author:** ![benkj](https://avatars.discourse-cdn.com/v4/letter/b/848f3c/32.png) [@benkj](https://discourse.julialang.org/u/benkj)\
**Post date:** [October 29, 2020, 5:27pm UTC](https://discourse.julialang.org/t/metaprogramming-and-variable-scope-again/49248/4 "2020-10-29T17:27:14Z")

</div>

thanks, this solves my issue
