1
votes

I have a very simple Julia code:

x=0
for n in 1:10
    x = x + n
end
println(x)

And it gives me an error:

ERROR: LoadError: UndefVarError: x not defined

Stacktrace:

[1] top-level scope at /home/piotr/julia_codes/t4.jl:3

[2] include(::Module, ::String) at ./Base.jl:377

[3] exec_options(::Base.JLOptions) at ./client.jl:288

[4] _start() at ./client.jl:484

in expression starting at /home/piotr/julia_codes/t4.jl:2

What should I check?

2

2 Answers

4
votes
  1. Julia 1.6.0 has changed how scoping mechanism within REPL so now this works
  2. Basically your goal is to have the code in functions rather than "naked"
  3. Version independent code could look like this (or you could use global as in the other answer):
let x=0
    for n in 1:10
        x = x + n
    end
    println(x)
end
2
votes

Try this

x=0
for n in 1:10
    global x
    x = x + n
end
println(x)

This is related to the scope in JuliaLang.

For more info refer to this JuliaLang discussion.