Hi there, I’m having some troubles understanding variable scoping in macros. Here is the simplest code to show my problems
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?
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):