What you want to have is
julia> x = 33
33
julia> macro inc(a)
esc(:($a = $a + 1))
end
julia> @show macroexpand(:(@inc x))
macroexpand($(Expr(:quote, :(@inc x)))) = :(x = x + 1)
:(x = x + 1)
julia> @show @inc x
@inc(x) = 34
34
1. You need esc I think otherwise
julia> macro inc(a)
:($a = $a + 1)
end
julia> @show macroexpand(:(@inc x))
macroexpand($(Expr(:quote, :(@inc x)))) = :(#6#x = #6#x + 1)
:(#6#x = #6#x + 1)
It is just garbage ending with `x`
2. You should feed an expression to macroexpand to get the resulting
expression from the macro
On Wednesday, May 11, 2016 at 1:21:09 PM UTC+3, Ford Ox wrote:
>
>
> *My struggle with macros*
> Lets code macro for increment, that should be fairly easy right?
> x = 33
> macro inc(x)
> :(x = x + 1)
> end
>
> @show @inc x
>
>> LoadError: UndefVarError: x not defined
>
>
> Hmm, it's not so easy as I thought, I must be missing some very basic
> knowledge, lets see whats happening inside. In docs they say* macroexpand*
> should be used for debugging.
> x = 33
> macro inc(x) x end
> @show macroexpand(@inc x)
>
> macro inc(x) :x end
> @show macroexpand(@inc x)
>
> macro inc(x) :($x) end
> @show macroexpand(@inc x)
>
>> macroexpand(@inc(x)) = 33
>> macroexpand(@inc(x)) = 33
>> macroexpand(@inc(x)) = 33
>>
>
> Little confused : That didn't tell me anything... What type is *x *anyway?
> x = 33
> macro inc(x)
> show(x)
> x
> end
> @inc(x)
>
>> :x
>>
>
> So it is a symbol. In that case, why "*macro inc(x) :x end*" evaluates as
> *"33"
> *instead of "*:x*"??
> ...
> After hour of playing with macros I finally realize how to make use of
> *macroexpand()*.
> x = 33
> v = 3
> w = :v
>
> ex = :(:(w = w + 1))
>
> macro inc(x)
> :(:(x = x + 1))
> end
>
> @inc v
> @show macroexpand(eval(ex))
>
>> macroexpand(eval(ex)) = :(w = w + 1)
>>
>
> And I also realize that I need to use interpolation...
> x = 33
> v = 3
> w = :v
>
> ex = :(:($w = $w + 1))
>
> macro inc(x)
> :(:($x = $x + 1))
> end
>
> @show macroexpand(eval(ex))
>
>> macroexpand(eval(ex)) = :(v = v + 1)
>>
>
> Oh, that looks very nice. That's exactly what I wanted. My macro should
> work exactly in the same way, since x ~ w and eval() is called
> automatically when the line is executed...
> @show @inc v
>
>> @inc(v) = :(33 = 33 + 1)
>>
>
> WOW, WTF?
>
>
>
>
>
>