# How to provide a macro in a module (package) as it would be used in the user code (i.e. with access to the user current scope)

**URL:** <https://discourse.julialang.org/t/how-to-provide-a-macro-in-a-module-package-as-it-would-be-used-in-the-user-code-i-e-with-access-to-the-user-current-scope/52815>\
**Category:** General Usage\
**Created:** [January 4, 2021, 10:26am UTC](https://discourse.julialang.org/t/how-to-provide-a-macro-in-a-module-package-as-it-would-be-used-in-the-user-code-i-e-with-access-to-the-user-current-scope/52815 "2021-01-04T10:26:46Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sylvaticus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sylvaticus/32/203883_2.png) [@sylvaticus](https://discourse.julialang.org/u/sylvaticus)\
**Post date:** [January 4, 2021, 10:26am UTC](https://discourse.julialang.org/t/how-to-provide-a-macro-in-a-module-package-as-it-would-be-used-in-the-user-code-i-e-with-access-to-the-user-current-scope/52815/1 "2021-01-04T10:26:47Z")

</div>

Let’s say I want to provide users with the above macro:

```julia
macro customLoop(controlExpr,workExpr)
  return quote
    for i in $controlExpr
      $workExpr
    end
  end
end

```

If this macro is evaluated in Main then the user can just use the above code and everything is fine:

```julia
finalLoopIdx = 4
@customLoop 1:finalLoopIdx println(i)

```

If I however set the macro inside a module, e.g.:

```julia
module foo
export @customLoop2

macro customLoop2(controlExpr,workExpr)
  return quote
    for i in $controlExpr
      $workExpr
    end
  end
end

end

```

Then the above code would NOT work, as `finalLoopIndex` is out of scope for the macro (maybe this is the issue with the so-called “macro hygiene” ???):

```julia
using .foo
@customLoop2 1:finalLoopIndex println(i) # UndefVarError: finalLoopIndex not defined

```

How can a package can provide a macro that behaves like it is in the same module (e.g. `Main`) of the user, i.e. it has access to the variables into the user’s current scope ?  
Are there other ways to “solve” this kind of task ?

---

<div class="post-metadata">

**Author:** ![sylvaticus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sylvaticus/32/203883_2.png) [@sylvaticus](https://discourse.julialang.org/u/sylvaticus)\
**Post date:** [January 4, 2021, 10:33am UTC](https://discourse.julialang.org/t/how-to-provide-a-macro-in-a-module-package-as-it-would-be-used-in-the-user-code-i-e-with-access-to-the-user-current-scope/52815/2 "2021-01-04T10:33:00Z")

</div>

I think I found the answer here: [scope of expressions and variables in Julia macro in modules - Stack Overflow](https://stackoverflow.com/questions/42299444/scope-of-expressions-and-variables-in-julia-macro-in-modules)
