编辑A内部的值



在朱莉娅(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

为什么?

以来它创建一个新的 local 范围:

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>

请参阅:

  • 全局关键字
  • 本地范围
  • 避免全局变量

最新更新