String as a variable name

Doing it as a macro seems to work correctly inside a function (i.e. variables are created only in the local scope):

macro string_as_varname_macro(s::AbstractString, v::Any)
	s = Symbol(s)
	esc(:($s = $v))
end

function string_as_varname_function(s::AbstractString, v::Any)
	s = Symbol(s)
	@eval (($s) = ($v))
end

function test()
	string_as_varname_function("a",2)
	@string_as_varname_macro("b",3)
	println("(a,b) = ($a,$b)")
end

test()
isdefined(:a) && println("a = $a")
isdefined(:b) && println("b = $b")
nothing

Output:

(a,b) = (2,3)
a = 2

I’ve only been working with Julia for a few weeks, so please explain if this has some unintended side effect.

3 Likes