Julia 1.0 UndefVarError - Scope of Variable

给你一囗甜甜゛ 提交于 2019-12-01 10:33:41

问题


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:

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

In Julia 0.7 (and in most of other languages), we could expect num = 1 after the loop. However, it will incur UndefVarError: num not defined in Julia 1.0. I know that by using let I can do this

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

It will print out 1. But I do want to get the num = 1 outside the loop and the let block. Some answers suggest putting all code in a let block, but it will incur other problems including UndefVarError while testing line-by-line. Is there any way instead of using let blocking? Thanks!


回答1:


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.




回答2:


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

function testscope()
    num = 0
    for i = 1:5
        if i == 3
            num = num + 1
        end
    end
    return num
end


julia> t = testscope()
1

The unexpected behaviour is only in REPL. More on this here



来源:https://stackoverflow.com/questions/52396269/julia-1-0-undefvarerror-scope-of-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!