Eval symbol on LHS for assignment

the following code does not work, but can julia allow me to do this?

julia> names = [ :x, :y ];

julia> eval(names[1])= 42  ## should be the same as x=42

julia> x
42

Try,

julia> names=[:x,:y]
2-element Array{Symbol,1}:
 :x
 :y

julia> @eval $(names[1]) = 42
42

julia> x
42

2 Likes
names= [ :x, :y ]

function work( values::Vector{Int} )
    println("using $(values), but the eval inside work() fails")
    @eval $(names[1])= values[1]
    println("or this fails, too")
    for i=1:length(values);	@eval $(names[i])= values[i]; end
    println("now we can work with x=$x and y=$y")
end

vals= [ 1, 2 ]
@eval $(names[1])= vals[1]
println("in main, this worked with x=$x")

work( vals )

closely related. how could this be made to work?

There’s no direct way to do this with eval since that only evaluates things in the global scope, not the function scope. Is there any reason,

function work(x,y)
  # your code here
end

vals = [1,2]
work(vals...)

wouldn’t work?

no, it would not just work…it is much better! argggh!

The only restriction is that you cannot get and set a local variable by runtime name. Everything else is fine. If you want to do just this, then no, don’t think about it. Otherwise, you should specify what does “work” mean, or what you want. Just getting the code to not raise an error is trivial but it may or may not do what you want.

It’s also much better to NOT use @eval to learn about eval or macro. It blends multiple scope and evaluaiton rules together making it very confusing before you know all of them well already. You should use the eval function first before you know all the rules.