问题
Can someone resolve this macro error I'm having, it only started happening in version 0.6:
mutable struct Foo
x::Int
end
macro test(myfoo)
quoteblock =
quote
myfoo.x += 1
end
return quoteblock
end
function func(myfoo)
@test myfoo
println(myfoo.x)
end
foo = Foo(3)
func(foo)
In theory this should just replace the line @test myfoo
in the function func
with myfoo.x += 1
at compile time, which should work, but instead I get the error:
UndefVarError: myfoo not defined
回答1:
The corresponding change-notes are listed here:
When a macro is called in the module in which that macro is defined, global variables in the macro are now correctly resolved in the macro definition environment. Breakage from this change commonly manifests as undefined variable errors that do not occur under 0.5. Fixing such breakage typically requires sprinkling additional escs in the offending macro (#15850).
so the answer is to escape myfoo
:
macro test(myfoo)
quote
$(esc(myfoo)).x += 1
end
end
来源:https://stackoverflow.com/questions/45400875/julia-v0-6-macro-inside-function