I was expecting the second and third code to behave exactly like first, except neither behave the same
# First
i = 0
let
i = 1
Fs = Vector{Any}(undef, 2)
while i <= 2
let
j = i
Fs[j] = ()->j
end
i += 1
end
println("$(Fs[1]())")
println("$(Fs[2]())")
println("inner $i")
end
println("global $i")
#= output
1
2
inner 3
global 0
=#
# Second
i = 0
let
i = 1
Fs = Vector{Any}(undef, 2)
while i <= 2
let
i = i
Fs[i] = ()->i
end
i += 1
end
println("$(Fs[1]())")
println("$(Fs[2]())")
println("inner $i")
end
println("global $i")
#= output
3
3
inner 3
global 0
=#
# Third
i = 0
let
local i = 1
Fs = Vector{Any}(undef, 2)
while i <= 2
let
local i = i
Fs[i] = ()->i
end
i += 1
end
println("$(Fs[1]())")
println("$(Fs[2]())")
println("inner $i")
end
println("global $i")
#=
ERROR: LoadError: UndefVarError: #1#i not defined
Stacktrace:
[1] top-level scope at C:\dev\lang\julia\tester3.jl:9
[2] include(::Function, ::Module, ::String) at .\Base.jl:380
[3] include(::Module, ::String) at .\Base.jl:368
[4] exec_options(::Base.JLOptions) at .\client.jl:296
[5] _start() at .\client.jl:506
in expression starting at C:\dev\lang\julia\tester3.jl:3
=#
- I assumed that local is redundant in a let block, and that you only need to specify global otherwise local will be assumed
- the top let statement seem to be able to create a local i variable, but not the inner let
- The inner let uses the outer i and raises and error when i try to force to make a local copy