Julia v0.6宏内部函数 [英] Julia v0.6 macro inside function
问题描述
有人可以解决我遇到的这个宏错误,它仅在版本0.6中才开始发生:
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)
从理论上讲,这应该只在编译时用myfoo.x += 1
替换函数func
中的行@test myfoo
,这应该可以,但是我得到了错误:
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
推荐答案
The corresponding change-notes are listed here:
在定义该宏的模块中调用宏时, 宏中的全局变量现在可以在宏中正确解析 定义环境. 这种变化的破坏通常表现为 在0.5以下不会发生的未定义变量错误.修复这样的 破损通常需要在 令人反感的宏(#15850).
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).
所以答案是逃避myfoo
:
macro test(myfoo)
quote
$(esc(myfoo)).x += 1
end
end
这篇关于Julia v0.6宏内部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!