PiotrB
PiotrB

Reputation: 143

Why Julia gives error on very simple code?

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?

Upvotes: 1

Views: 1401

Answers (2)

Jaswant Singh
Jaswant Singh

Reputation: 10759

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.

Upvotes: 2

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42244

  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

Upvotes: 4

Related Questions