Hans Bambel
Hans Bambel

Reputation: 956

Julia: Scope of variables in a nested loop

I'm trying to change a variable in a for-loop which is in a while-loop. I know that the scope of variables in a for-loop are local by default, thus I put a global in front of the variable I want to change. This works for i but not for turn. When I add global in front of turn in the for-loop, I get the following error:

ERROR: LoadError: syntax: global turn: turn is a local variable in its enclosing scope

i = 0
while(i <= 3)
    global i += 1
    turn = 0
    for j = 1:2
        turn += 1  # if I add a global in front of turn I get an error message
        println("Turn: ", turn)
    end
end

The result is:

Turn: 1
Turn: 2
Turn: 1
Turn: 2
Turn: 1
Turn: 2
Turn: 1
Turn: 2

But what I want is:

Turn: 1
Turn: 2
Turn: 3
Turn: 4
Turn: 5
Turn: 6
Turn: 7
Turn: 8

How am I able to change turn in the nested for-loop?

Upvotes: 0

Views: 898

Answers (1)

amanbirs
amanbirs

Reputation: 1108

I am able to get the desired ouptut by moving turn outside the while loop. For the record, I also do not get an error when running your code. What version of Julia are you using?

i = 0
turn = 0
while(i <= 3)
    global i += 1
    for j = 1:2
        global turn += 1  
        println("Turn: ", turn)
    end
end

Upvotes: 1

Related Questions