There are tools mentioned in the Metaprogramming section of the manual
which will help to better understand what is going on. In particular,
macroexpand.

http://docs.julialang.org/en/latest/manual/metaprogramming/#basics

Are there better ways to do this, is it OK to use eval() in this context?
>

The general advice is "don't use eval in a macro". Among other issues,
doing so will usually lead to slow code. A macro should not (generally)
have side-effects like printing, but rather should return an expression
that does what you want when itself evaluated.

On Wed, Mar 11, 2015 at 8:37 AM, Kaj Wiik <[email protected]> wrote:

> I have a problem in using variables as argument for macros. Consider a
> simple macro:
>
> macro testmacro(N)
>     for i = 1:N
>         println("Hello!")
>     end
> end
>
> @testmacro 2
>
> Hello!
> Hello!
>
>
> So, all is good. But if I use a variable as an argument,
>
> n = 2
> @testmacro n
>
>
> I get an (understandable) error message "ERROR: `colon` has no method
> matching colon(::Int64, ::Symbol)".
>
> Is this the correct place to use eval() in macros, like
>
> macro testmacro(N)
>     for i = 1:eval(N)
>         println("Hello!")
>     end
> end
>
> This seems to work as expected. I tried multitude of combinations of
> dollar signs, esc, quotes and brackets, none of them worked :-), got
> "ERROR: error compiling anonymous: syntax: prefix $ in non-quoted
> expression"...
>
> Are there better ways to do this, is it OK to use eval() in this context?
>
> Thanks,
> Kaj
>
>

Reply via email to