我有一个简单的while循环,它使用i = 1作为索引。
global i = 1
n = rows
while i <= n
if prod(isa.(collect((y)[i,:]),Number))==0
delete!(y,i)
x_axis = x_axis[1:end .!= i]
n -= 1
end
i += 1
end但我发现了一个错误:
UndefVarError: i not defined
top-level scope@Local: 23我甚至使我的i全球,根据建议,对一些类似的问题,所以,但错误仍然存在。我是在Pluto.jl上运行这个的,所以可能是环境问题。
发布于 2021-03-22 09:13:25
首先,请注意,如果使用Julia v1.5+,则不需要使i成为全局的(下面的示例是当前稳定版本v1.5.4):
julia> i = 1
1
julia> while i < 5
println(i)
i += 1 # <----- this works in Julia v1.5+
end
1
2
3
4但是,您似乎使用了以前版本的JuliaV1.4,在这种情况下,我认为Logan给了您答案:您需要在i循环的范围内使while成为全局的。正如Logan提到的,尝试添加global,在其中添加i,如本例所示,从while函数的文档中添加:
julia> i = 1 ;
julia> while i < 5
println(i)
global i += 1 # <------------ Try this!
end
1
2
3
4还请注意,如果您的while循环位于函数中,则不需要指定它是全局的,如
julia> function foo(istart)
i = istart
while i < 5
println(i)
i += 1 # <-- 'global' not needed inside a function!
end
end
foo (generic function with 1 method)
julia> foo(1)
1
2
3
4发布于 2021-03-22 10:35:59
你说的是“模棱两可的软范围案”。
简而言之:在(软)本地作用域中分配局部变量取决于代码是否在"REPL上下文“中。
对于"REPL上下文“,我指的是REPL和在本例中作为REPL行为的所有环境,例如:
julia> i = 0
julia> while i < 3
i += 1
@info i
end
[ Info: 1
[ Info: 2
[ Info: 3相反,来自非交互式上下文的代码,如文件、eval和Pluto,其作用如下:
julia> code = """
i = 0
while i < 3
i += 1
@info i
end
"""
julia> include_string(Main, code)
┌ Warning: Assignment to `i` in soft scope is ambiguous because a global variable by the same name exists: `i` will be treated as a new local. Disambiguate by using `local i` to suppress this warning or `global i` to assign to the existing global variable.
└ @ string:3
ERROR: LoadError: UndefVarError: i not defined所有这些都是为了确保REPL的使用方便,并避免大规模使用julia带来的副作用。
详细信息这里。
要解决这个问题,您可以按照建议使用global,或者将代码包含在函数中。
发布于 2021-03-24 16:08:33
Pluto隐式地将一个单元格封装到一个函数中,请参阅https://github.com/fonsp/Pluto.jl/pull/720,因此不需要global注释或显式包装到函数中。
将以下内容放入冥王星单元中对我有用:
begin
i = 1
n = 100
while i<=n
if i % 2 == 0
n -= 1
end
i += 1
end
end当在单元格内使用宏(这会阻止Pluto收集反应性信息)时,将禁用隐式函数包装,因此,由于Julia的作用域规则,以下内容在Pluto中无效:
begin
i = 1
n = 100
while i<=n
if i % 2 == 0
n -= 1
end
@show i += 1
end
end抛出:
UndefVarError: i not defined
top-level scope@Local: 5[inlined]
top-level scope@none:0https://stackoverflow.com/questions/66739127
复制相似问题