@Tamas_Papp Reading discussions like this was definitely confusing (as confusing as the Julia scoping rules can be) AND helpful for me.
Loops
and try-catch
creating a local scope may have reasons (with try-catch-finally
creating 3 separated scopes being expecially piquant). However normally you would want to pass the results to the āouter worldā.
For myself, Iād sum up the following rules to avoid scoping problems:
-
global is evil. Especially never call
loop
ortry-catch
constructs on the global (script) scope - Put everything into functions as early as possible
- Otherwise at least put
loop
ortry-catch
into alet
block - Initialize the variable to be used to return results before the
loop
ortry-catch
construct. If the variable starting value is not used in the loop, initialize it withnothing
Like the following
let
k = nothing
for i in 1:2
k = i
end
@show k
end
function f2()
p = 0
for j in 1:4
p += j
end
return p
end
@show f2()
function tryit(sq)
ll = mm = nothing
try
mm = 9
ll = sqrt(sq)
catch
ll = sqrt(mm)
finally
ll += mm
end
return ll
end
@show tryit(10.0)
@show tryit("ten")
k = 2
f2() = 10
tryit(10.0) = 12.16227766016838
tryit("ten") = 12.0