For some reason, I had to put quote...end block in the macro and ex is generated programmatically. This code works.
macro addsum_out()
quote
ex = :(x+y)
sum(eval(ex))
end
end
x = [1 1 1]
y = [2 2 2]
z2 = @addsum_out
When the macro is put inside a module, it no longer works:
module MyModule
export @addsum
macro addsum()
quote
ex = :(x+y)
sum(eval(ex))
end
end
end
using MyModule
x = [1 1 1]
y = [2 2 2]
z = @addsum
It says:
ERROR: LoadError: UndefVarError: x not defined
I think I should put esc somewhere, to evaluate the expression ex in the main scope outside the module. What should I handle this?
evalshould not be used in macros. What are you trying to do?evaloperates at module-global scope. Look atmacroexpand( :(@addsum) )and notice theMyModule.eval. Anyway, it is completely unnecessary. You should returnesc(:(x + y) )instead.