unpack can just look at its inputs and build up Expr() objects piece-by-piece.
Here’s an example of building up some indexing code from your first example:
function makeindex(name::Symbol, indices::Vector{Int})
n = length(indices)
res = Array(Expr, n)
for i in 1:n
res[i] = Expr(:ref, name, indices[i])
end
return res
end
julia> makeindex(:p, [1, 2])
2-element Array{Expr,1}:
:(p[1])
:(p[2])
But, as you’ve said, this is a pretty strange use of metaprogramming since
you’re trying to work with values, even though macros should mostly operate on
syntax. In addition, you seem to want to work with the value of p and the
symbolic name p at the same time, which is particularly complicated.
One way to think about macros that helped me a lot is to envision them all
taking place during a single compile-time pass through your codebase. As such,
they should never depend on the value of anything that isn’t statically
available before your program runs. This restriction isn’t actually a real one,
but it may help push you in the right direction.
— John
On Mar 14, 2014, at 7:44 AM, Yuuki Soho <[email protected]> wrote:
> I'm trying to write an unpack macro, just to learn a bit about
> meta-programming (I get it's probably not the best idea,
> but sometimes you learn a lot doing stupid things), but I have to say than
> even after reading three times the doc,
> I have no idea how to do it. I wanted to do something like that:
>
> n = [:a,:b]
> p = [1 2]
>
> @unpack n p
>
> being transformed to:
>
> a = p[1]
> b = p[2]
>
> But that doesn't seem to be possible because the unpack macro just get the
> expressions "n" and "p", so there's not much you can do there.
> It seems I need an unpack function first to create the correct expression:
>
> @setvariables unpack(n,p)
>
> Where unpack unpack(n,p) generate the expression "a b 1 2", any ideas how I
> can do that ?