galacticus
galacticus

Reputation: 19

I'm getting the following error: "top-level scope at ./REPL[1]:4" when I run my julia program

So here's the code I was trying to execute in Julia:

i = begin
  i = 5
  while(i<=10)
  println(i)
  i+=1
  end
end

It's just basically a simple code to print the value of i from 5 to 10 but it's messing with me

Upvotes: 1

Views: 1271

Answers (2)

Nathan Boyer
Nathan Boyer

Reputation: 1474

Your issue is scope. When you enter into a loop, variables created inside the loop are local to the loop and destroyed after it exits. i is not currently defined inside your while loop, so you get the error. The quick fix is to tell Julia you want the loop to have access to the global i variable you defined at the top by adding global i immediately after the while statement. You also don't need the begin block, and naming the block i is immediately overwritten by the next statement defining i.

Upvotes: 1

Simeon Schaub
Simeon Schaub

Reputation: 775

Are you in the REPL? What you are probably running into is that begin does not introduce its own scope, so i = 5 declares i as a global variable. Because while does introduce its own scope, if you do println(i), it only looks for i in its local scope where it is not defined, because i exists only as a global variable. You can add a line global i at the beginning of the body of the while loop to tell all code after that to use the global i, but note that global variables come with their own performance caveats. An arguably better solution would be to use let instead of begin, which does introduce a new scope, but note that then you can of course not access i afterwards, because it is now only local to the let block.

This behavior will actually be changed in the upcoming release of Julia 1.5, so your code should then just work.

Upvotes: 1

Related Questions