I have just started using Julia. I am trying to use eval (in Julia) in order to define a set of variables in a function. Let's say I want to set v1 equal to 2:
function fun_test(varargs...)
v1 = 0;
if length(varargs) > 0
j = collect(linspace(1,length(varargs)-1,length(varargs)/2));
for i in j
expr_vargs = parse("$(varargs[i]) = $(varargs[i+1]);");
eval(expr_vargs);
end
end
println(v1)
end
Calling the function as:
fun_test("v1", "2");
It doesn't work, since println returns 0 (the initial value of v1). However, if I run an analogous eval call in the Julia's terminal, then it works.
Could you please clarify why it doesn't work and how to fix it?
expr_vargsis fine. It's theeval... - Memmingevalworks in the global scope, butv1is local because of the linev1=0. - Chris Rackauckasevalworks in the global scope. Other relevant StackOverflow questions (using google): stackoverflow.com/questions/21267962/… stackoverflow.com/questions/28882241/… stackoverflow.com/questions/20174352/julia-speeding-up-eval - Dan Getz