tlamadon
tlamadon

Reputation: 970

use macro to extract several object fields in Julia

I have a structure, from which I want to access repeatedly the fields to I load them in the current space like this (where M is type with fields X and Y):

X = M.X
Y = M.Y

in R, I often use the with command to do that. For now I would just like to be able to have a macro that expends that code, something along the lines of

@attach(M,[:X,:Y])

I am just not sure how exactly to do this.

Upvotes: 1

Views: 338

Answers (1)

Jeremy Wall
Jeremy Wall

Reputation: 25245

I've included in this answer a macro that does pretty much what you describe. Comments explaining what's going on are inline.

macro attach(struct, fields...)
    # we want to build up a block of expressions.
    block = Expr(:block)
    for f in fields
        # each expression in the block consists of
        # the fieldname = struct.fieldname
        e = :($f = $struct.$f)
        # add this new expression to our block
        push!(block.args, e)
    end
    # now escape the evaled block so that the
    # new variable declarations get declared in the surrounding scope.
    return esc(:($block))
end

You use it like this: @attach M, X, Y

you can see the generated code like so: macroexpand(:(@attach M, X, Y)) which will show something like this:

quote
    X = M.X
    Y = M.Y
end

Upvotes: 6

Related Questions