colinfang
colinfang

Reputation: 21757

How to do string interpolation within a given context?

Is there a macro f that allows to apply string interpolation within a given context?

@f("abc$x", x=3) == "abc3"

Or maybe a function g

g("abc\$x", x=3)

Upvotes: 4

Views: 93

Answers (1)

tim
tim

Reputation: 2096

You can introduce a new context with a let block. Here is a macro that does that:

macro f(s, args...)
    args = [:($(esc(a.args[1])) = $(esc(a.args[2]))) for a in args]
    quote
        let $(args...)
            $(esc(s))
        end
    end
end

z = 5
x = 1


@f("abc$x, $(2y), $z", x=3, y = 2x)
# "abc3, 12, 5"

Note the difference to a function, where y = 2x would refer to x in the scope of the caller, i.e., to x=1. So I'm not sure if this is what you need.

Upvotes: 6

Related Questions