This issue has bothered me for a long time. Previously I thought it was related to my program, but the following example shows it should not.
As could be seen in the snapshot
- The REPL does have access to variable
x in the first loop.
- Then suddenly the access is lost when I want to
x += 1 in the second loop.
I mainly use Julia for scientific computation and maybe there is something syntactic I am not aware of. But here I believe
x is a global variable and it could be accessed when session is open.
Could someone help me, thank you in advance.
Loops have their own scope as of Julia 1.0. I’m a bit puzzled about why the first loop works, but there’s tons of discussion about this, cf this, this, and this. I’ll bet the answer lies somewhere in there, but hopefully someone else can explain.
(Note though that (I don’t think) either of those solutions I linked were implemented)
Oh also, as a general rule, please copy-paste and quote your code rather than posting screenshots. In this case it’s trivial, but it just makes it easier if people can copy your code and paste it into their own repl to reproduce. See here
Which version are you on? With the 1.1 Julia (
Julia Version 1.1.0
Commit 80516ca202 (2019-01-21 21:24 UTC)
OS: Windows (x86_64-w64-mingw32)
CPU: Intel(R) Core(TM) i7-6650U CPU @ 2.20GHz
LLVM: libLLVM-6.0.1 (ORCJIT, skylake)
JULIA_EDITOR = "C:\Users\PetrKrysl\AppData\Local\atom\app-1.37.0\atom.exe" -a
JULIA_NUM_THREADS = 2
) I get the same result as you. I think the scoping rules (New scope solution - #53 by StefanKarpinski) may be in effect.
In the first case, the variable is read, and the globally visible
x is printed.
In the second case, the variable is written into (it is incremented), and therefore it is assumed to be a local variable, and since the local
x does not exist, an error is reported.
You may get the second loop to work as
julia> for i in 1:3
global x += 1