Check out the documentation on the scoping rules: Scope of Variables · The Julia Language
As an example, consider
n = 0
while rand() < 0.9
n += 1
end
println(n)
When run in the REPL, this works as intended (cf. @Benny 's reply):
julia> n = 0
julia> while rand() < 0.9
n += 1
end
julia> println(n)
18
If you put it in a file called script.jl, then running julia script.jl
in the terminal (or include("script.jl")
in the Julia REPL) yields
> julia script.jl
┌ Warning: Assignment to `n` in soft scope is ambiguous because a global variable by the same name exists: `n` will be treated as a new local. Disambiguate by using `local n` to suppress this warning or `global n` to assign to the existing global variable.
â”” @ (...)\script.jl:3
ERROR: LoadError: UndefVarError: `n` not defined in local scope
Suggestion: check for an assignment to a local variable that shadows a global of the same name.
Stacktrace:
...
The warning hints that
n = 0
while rand() < 0.9
global n
n += 1
end
println(n)
in script.jl will solve the problem, as it indeed does:
> julia script.jl
8
In most situations the best solution (also for performance) is just to avoid (non-typed / non-const
) global variables entirely, e.g. by using a function (cf. @ArchieCall ). If you put
function main()
n = 0
while rand() < 0.9
n += 1
end
println(n)
end
main()
in our script.jl, you get
julia> include("script.jl")
4
This also works in the REPL:
julia> function f()
n = 0
while rand() < 0.9
n += 1
end
println(n)
end
f (generic function with 1 method)
julia> f()
8
If you had previously defined a global variable called n
, then that is completely unrelated to the local n
inside f
:
julia> n
18