ShoutOutAndCalculate
ShoutOutAndCalculate

Reputation: 587

Julia 1.1 x=x+1 in for loop returned error

I'm using Julia 1.1 and I tried to use for loop do the following simple things:

i_index=1;
for index in (1:100)
    i_index=i_index+1;
end

However, I got an error saying:

ERROR: UndefVarError: i_index not defined

I have tried several times and variations, but they all failed to work. Is this a bug? or why Julia can't do this simple iterative addition?

Upvotes: 5

Views: 238

Answers (1)

Inon Peled
Inon Peled

Reputation: 711

In the REPL:

i_index=1;
for index in (1:100)
    global i_index;
    i_index=i_index+1;
end

This is because of variable scope, see in Julia documentation. Note that the examples there pertain to the REPL.

Upvotes: 1

Related Questions