title: Evaluate a local variable inside a Julia macro
body: <p>I'm writing a Julia macro that takes an expression and serializes it, so that I can run it somewhere else. The macro therefore takes the expression and replaces all symbols with variables. The expression is then serialized and evaluated somewhere else.</p>
  <p>My problem is related to evaluating variables that are not in the global scope. I.e. the following works fine, as <code>a</code> is defined in the global scope:</p>
  <pre><code>macro myprintf(ex)
      print(eval(ex))
  end
  
  # works 
  a = 2
  @myprintf a
  </code></pre>
  <p>This throws an error as the macro doesn't see <code>a</code>, which is defined in the local scope of the loop (run in a new session):</p>
  <pre><code>macro myprintf(ex)
      print(eval(ex))
  end
  
  # UndefVarError: a not defined
  for j=1:3
      a = 2
      @myprintf a
  end
  </code></pre>
  <p>Is there any way I can access <code>a</code> inside the macro if it is defined in a local scope such as a loop? I'm aware that I'm not necessarily using macros as intended as I am calling <code>eval</code> on the expression inside the macro definition. The overall idea is that I want to serialize the expression that's passed to the macro and evaluate it somewhere else later (e.g. in a different Julia session).</p>