I would like to achieve something along the following lines: when I write @all(A)
, it should replace it with A[ix,iy,iz]
in the caller’s scope (ix
, iy
and iz
are defined in the caller’s scope).
So, I wrote the following macro:
macro all(A) :( esc($A[ix,iy,iz]) ) end
However, it does not work as wished:
$>julia
julia> macro all(A) :( esc($A[ix ,iy ,iz ]) ) end
@all (macro with 1 method)
julia> B = ones(2, 3, 1)
2×3×1 Array{Float64,3}:
[:, :, 1] =
1.0 1.0 1.0
1.0 1.0 1.0
julia> ix = 2;
julia> iy = 1;
julia> iz = 1;
julia> @macroexpand @all(B)
:((Main.esc)((Main.B)[Main.ix, Main.iy, Main.iz]))
julia> @all(B)
:($(Expr(:escape, 1.0)))
julia> eval(@all(B))
ERROR: syntax: invalid syntax (escape #<julia: 1>)
Stacktrace:
[1] eval at ./boot.jl:319 [inlined]
[2] eval(::Expr) at ./client.jl:393
[3] top-level scope at none:0
And if I try to call the macro from within a function, I get:
julia> function f()
C = ones(5,5,5);
ix = 1;
iy = 2;
iz = 1;
println(@macroexpand @all(C))
println(@all(C))
end
f (generic function with 1 method)
julia> f()
(Main.esc)((Main.C)[Main.ix, Main.iy, Main.iz])
ERROR: UndefVarError: C not defined
Stacktrace:
[1] f() at ./none:7
[2] top-level scope at none:0
Questions
- When called within the function
f()
, why does the macro expand to an expression containingMain.C
and notf.C
(andMain.ix
and notf.ix
etc)? - How can I fix this macro to achieve what I described at the beginning?
Thanks!