Global variables not accessible inside loop

#1

I am trying to execute this simple lines of code, but keep getting an undef error, although I explicitly define my variable to be global.

global t = 1;
for i in 1:10
t+=0.1;print("\ni=",i,", t=",t);
end

This gives

ERROR: UndefVarError: t not defined
I am using Julia 1.1.0. Can you help me understand what I am doing wrong.

0 Likes

#2

You need global t += 0.1 in the loop to modify a global.

0 Likes

#3

The keyword global is at the wrong place.

t = 1;
for i in 1:100  
    global t += 0.1
    @show t i
end
2 Likes

#4

If you are an introductory user, then I suggest for now either (1) using Jupyter for exploration, as it is more intuitive; or (2) wrap code with loops in functions if working in the console or top level scripts.

0 Likes

#5

Or just use the global keyword if you want to modify a global variable from inside a loop, function or other scope block.

11 Likes

#6

Thanks. I will reread the manual and try to understand why this works.

0 Likes

#7

Thanks. I will try to get Jupyter.

0 Likes

#8

I will reread the manual and try to understand why this works. Thanks !

0 Likes

split this topic #9

4 posts were split to a new topic: Installing IJulia

0 Likes