Julia v0.6 macro inside function

老子叫甜甜 提交于 2020-01-04 14:13:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!