Raumschifffan
Raumschifffan

Reputation: 370

Global variable modifying macro

I am currently learning Julia and trying to get a hang of macros.
As an exercise I'm trying to make a function that modifies its first argument on a global context.
For the record I know about Ref(), I just wanted to try it with macros.
My current code is however giving me a running error, I do not understand.

macro mod(code::Expr)
    arg = code.args[1].args[2]
    expr = :($arg = 1)
    push!(code.args[2].args, Expr(:eval, expr))
    return code
end

@mod function f(x) end

x = 0
f(x)
println(x)

This should take the first variable of the function (x) and modify it to be 1.
Unfortunately, I get an error ERROR: LoadError: syntax: invalid syntax (eval (= #1#x 1)).
I tried multiple approaches with double qutoation, etc. but can't seem to get the hang of it.

Can somebody explain the error and maybe even provide a solution? Thank you!

Upvotes: 1

Views: 167

Answers (1)

jling
jling

Reputation: 2301

here's how you do it

julia> macro mod(code)
           arg = code.args[1].args[2]
           expr = :(global $arg = 1)
           push!(code.args[2].args, expr)
           esc(code)
       end
@mod (macro with 1 method)

julia> @mod function f(x) end
f (generic function with 1 method)


# equivalent to
# function f(x)
#     global x = 1
# end


julia> f(3)
1

julia> x
1

Upvotes: 2

Related Questions