I have been trying to write a Julia macro that takes Cmd objects and runs them inside a loop. The catch is that I want to use the local loop variables for interpolation in the command. I would write a function and use eval(), but eval() uses the global scope and so can't see the local loop variables.
Below is a simple example that demonstrates how string interpolation works, but the command interpolation fails:
macro runcmd(cmdExpr)
quote
for i in 1:2
println("i: $i")
run($cmdExpr)
end
end
end
@runcmd(`echo $i`)
outputs
i: 1
ERROR: i not defined
in anonymous at none:5
If I expand the macro I get
quote # none, line 3:
for #261#i = 1:2 # line 4:
println("i: $#261#i") # line 5:
run(Base.cmd_gen((("echo",),(i,))))
end
end
I am guessing the #261# part that is missing from the cmd_gen argument's reference to i is related to the problem, but I don't know for sure.
i
in yourquote
is not going to appear literally as ani
in the generated code. - IainDunning