Macro that defines function

This doesn’t work. What’s the reason why I can’t define a function as expanded from a macro? Or did I do something wrong?

module C  
    macro makefunc(ex)
        return quote
            wat() = $(esc(ex))
        end
    end
    @makefunc(123)
end
using .C
C.wat()       # ERROR: UndefVarError: wat not defined

It works:

julia> macro makefunc(ex)
           return quote
               wat() = $(esc(ex))
           end
       end
@makefunc (macro with 1 method)

julia> @makefunc(123)
#19#wat (generic function with 1 method)

julia> var"#19#wat"()
123

But you probably didn’t want to name it var"#19#wat". You could escape the entire expression instead of just ex.

4 Likes

Ah, right! This works. Thanks.

module C  
    macro makefunc(ex)
        return esc(quote
            wat() = $ex
        end)
    end
    @makefunc(123)
end
using .C
C.wat()    # 123
1 Like