在朱莉娅,我很惊讶以下各项不起作用:
# Make a random value
val = rand()
# Edit it *inside an if statement in a for loop*
for i in 1:10
println("current value of val = ", val)
if true
val = val * 2.
end
end
尝试运行此操作会导致:
UndefVarError: val not defined
问题似乎是if
语句。例如,此命令运行正常(除了不编辑val
!):
val = rand()
for i in 1:10
println("current value of val = ", val)
# if true
# val = val * 2.
# end
end
这是为什么?
答案 0 :(得分:3)
从Julia版本1.x开始,在循环中更新全局变量时,您需要使用 global 关键字,因为它会创建新的 < strong>本地 范围:
julia> val = rand()
0.23420933324154358
julia> for i in 1:10
println("Current value of val = $val")
if true
val = val * 2
end
end
ERROR: UndefVarError: val not defined
Stacktrace:
[1] top-level scope at ./REPL[2]:2 [inlined]
[2] top-level scope at ./none:0
julia> for i in 1:10
println("Current value of val = $val")
if true
global val = val * 2
end
end
Current value of val = 0.23420933324154358
Current value of val = 0.46841866648308716
Current value of val = 0.9368373329661743
Current value of val = 1.8736746659323487
Current value of val = 3.7473493318646973
Current value of val = 7.494698663729395
Current value of val = 14.98939732745879
Current value of val = 29.97879465491758
Current value of val = 59.95758930983516
Current value of val = 119.91517861967031
julia>
请参阅: