Julia 1.0 UndefVarError - Scope of Variable

后端 未结 2 1789
轮回少年
轮回少年 2021-01-14 19:54

I am moving from Julia 0.7 to 1.0. It seems that Julia\'s rule for the scope of variables changed from 0.7 to 1.0. For example, I want to run a simple loop like this:

2条回答
  •  花落未央
    2021-01-14 20:00

    This is discussed here.

    Add global as shown below inside the loop for the num variable.

    num = 0
    for i = 1:5
        if i == 3
            global num = num + 1
        end
    end
    print(num)
    

    Running in the Julia 1.0.0 REPL:

    julia> num = 0
    0
    julia> for i = 1:5
               if i == 3
                   global num = num + 1
               end
           end
    julia> print(num)
    1
    

    Edit

    For anyone coming here new to Julia, the excellent comment made in the answer below by vasja, should be noted:

    Just remember that inside a function you won't use global, since the scope rules inside a function are as you would expect:

    See that answer for a good example of using a function for the same code without the scoping problem.

提交回复
热议问题