在 for 循环中编辑一个值

Editing a value inside a for loop

在 Julia 中,我很惊讶以下不起作用:

# 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

这是为什么?

自 Julia 版本 1.x 起,您需要在循环内更新全局变量时使用 global 关键字,因为它创建了一个新的 local scope:

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>

参见: