How to interpolate strings in a given context?

Is there a macro fthat allows string interpolation to be applied in a given context?

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

Or maybe a function g

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

+4
source share
1 answer

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

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"

Pay attention to the difference in the function, which y = 2xwill refer to xthe volume of the caller, that is, to x=1. Therefore, I am not sure if this is what you need.

+5
source

Source: https://habr.com/ru/post/1661876/


All Articles