Calling Julia macro with runtime-dependent argument
<p>I would like to call a macro in a Julia package (<code>@defNLExpr</code> in JuMP) using an argument that is runtime dependent. The argument is an expression that depends on the runtime parameter <code>n</code>. The only way that I can think of doing this is something like the following:</p>

<pre><code>macro macro1(x)
  y=length(x.args);
  return esc(:(k=$y-1))
end

macro macro2(n)
  x="0";
  for i=1:n
    x="$x+$i"
  end
  x=parse(x);
  return :(@macro1($x))
end

n=rand(1:3)
println(n)
if (n==1)
  @macro2(1)
elseif (n==2)
  @macro2(2)
elseif (n==3)
  @macro2(3)
else
  error("expected n in 1:3")
end
println(k)
</code></pre>

<p>Here I have assumed that my runtime <code>n</code> will always be in the range 1-3. I use <code>macro2</code> to build-up all possible expressions for these different possible values of <code>n</code>, and call the external macro (which I have replaced by the simplified <code>macro1</code> here) for each of them. The calls to <code>macro1</code> are in <code>if</code> statements, so only the correct one (determined from the value of <code>n</code> at runtime) will actually be executed.</p>

<p>Although this seems to work, is there a more efficient way of achieving this?</p>