Cliff AB
Cliff AB

Reputation: 1190

Editing a value inside a for loop

In Julia, I'm very surprised the following does not work:

# 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

Trying to run this leads to:

UndefVarError: val not defined

The issue appears to be the if statement. For example, this runs fine (other than not editing val!):

val = rand()
for i in 1:10
    println("current value of val = ", val)
#    if true
#        val = val * 2. 
#    end
end

Why is this?

Upvotes: 1

Views: 102

Answers (1)

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

Since Julia version 1.x, you need to use the global keyword, when updating a global variable inside a loop, because it creates a new 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>

See:

Upvotes: 3

Related Questions