Global var Meta.parse in loop no vars in Main

Where are my vars p1 to p10

julia> for i=1:10
       var_name=Meta.parse("p$i")
       global var_name
       println(var_name)
       end
p1
p2
p3
p4
p5
p6
p7
p8
p9
p10

julia> varinfo()
name                    size summary
---------------- ----------- -------
Base                         Module
Core                         Module
InteractiveUtils 168.899 KiB Module
Main                         Module
Plots             24.362 MiB Module
ans                  0 bytes Nothing
var_name             0 bytes Symbol

julia> p1
ERROR: UndefVarError: p1 not defined

Paul

This is declaring var_name global, not whatever symbol stored in var_name to be global. You must use eval to create global variables from a runtime value but you also shouldn’t do that. What are you tryingn to accomplish?


On a side note, use Symbol("p$i") instead if you really want to generate variable names.

Just use an array:

p = zeros(10)
p[1]
1 Like

OK, thanks!

for i=1:10
var_name=Symbol("p$i")
@eval $var_name=rand()
println(var_name)
end

Paul

W dniu 2020-03-22 o 22:41, Yichao Yu via JuliaLang pisze:


for i=1:10

var_name=Symbol("p$i")
@eval $var_name=rand()
println(var_name)
println(@eval $var_name)

end

julia> p = rand(3)

julia> for i in 1:length(p)
           println("p[$i] = ", p[i])
       end
p[1] = 0.4687558912523784
p[2] = 0.6334251270809983
p[3] = 0.2641717376126682
1 Like