On Mon, 2016-10-24 at 10:37, Florian Oswald <florian.osw...@gmail.com> wrote: > I have something that this in C++ I would write like > > double f(double x){ > // do something with x > #ifdef MACROVAR > // do something else with x > #endif > return(x) > } > > I was trying to understand how i could use julia macro's to achieve > something similar. I have seen how the Logging.jl uses macros to this end, > at least that's how I understand > it: https://github.com/kmsquire/Logging.jl/blob/master/src/logging_macros.jl > . However I'm a bit unclear as to how to use this in my case. in my case, > the condition of whether or not to insert a piece of code is stored in a > custom type. Here is what I tried: > > # simplified type: > type Param > nD_rent :: Int > end > > # macro: > macro add_buy(p::Param) > quote > if $(esc(p.nD_rent)) > 4 > # insert some additional code > println("here comes additional code") > println(typeof(p)) > > else > println(typeof(p)) > :nothing > end > end > end
No, a macro receives the AST. Check this macro tmp(p) println(p) println(typeof(p)) end So your signature should probably just read: macro add_buy(p) ... end > *julia> **bk.@add_buy(p)* > > *ERROR: MethodError: no method matching @add_buy(::Symbol)* > > Closest candidates are: > > @add_buy(*::bk.Param*) at > /Users/florian.oswald/git/bk/bk.jl/src/solver.jl:641 > > > so, I have a type `Param`, and depending on the value in field nD_rent, I > would like to insert that code or not. thanks for any suggestions. That is not what your above macro does. And that is not what macros should do (ideally), they should be syntax transformations independent of the values. You can eval in a macro but that is *strongly* discouraged.