Defining an Anonymous Function in a Macro

This is a macro hygiene issue. If you use macroexpand, you’ll see that it is trying to use the global variables x and y instead of your new ones:

julia> @macroexpand @MakeMyStruct begin
           return x + y
       end
:((; Main.x, Main.y)->begin
          #= REPL[103]:2 =#
          return Main.x + Main.y
      end)

The fix is to use esc:

julia> macro MakeMyStruct(func_block)
           func = make_anon_function_expr(func_block; kwargs = (:x, :y))
           return esc(func)
       end
@MakeMyStruct (macro with 1 method)

julia> @macroexpand @MakeMyStruct begin
           return x + y
       end
:((; x, y)->begin
          #= REPL[105]:2 =#
          return x + y
      end)

julia> b = @MakeMyStruct begin
           return x + y
       end
#67 (generic function with 1 method)

julia> b(; x = 3, y = 2)
5
3 Likes