In Julia 1.0, I'm trying to implement a for loop along the lines of:
while t1 < 2*tmax
tcol = rand()
t1 = t0 + tcol
t0 = t1
println(t0)
end
However, I am getting errors that t1 and t0 are undefined. If I put a "global" in front of them, it works again. Is there a better way to handle this than by putting global variables all over my code?
The reason of the problem is that you are running your code in global scope (probably in Julia REPL). In this case you will have to use
global
as is explained here https://docs.julialang.org/en/latest/manual/variables-and-scoping/.The simplest thing I can recommend is to wrap your code in
let
block like this:This way
let
creates a local scope and if you run this block in global scope (e.g. in Julia REPL) all works OK. Note that I putt0, t1
at the end to make thelet
block return a tuple containing values oft0
andt1
You could also wrap your code inside a function:
and then call
myfun
with appropriate parameters to get the same result.