Global variable issue

basis, s, N, and everything else defined outside the loop are global variables, meaning they are defined at the topmost level. The line s=s+1 is inside the local scope of the while loop. Here Julia is not sure if you want to use the global s or define a new local s variable, so it throws an error. There are local and global keywords that can force one behavior or the other.

This issue is tricky to work around at first, especially with while loops when testing and learning the language (with scripts), but it will go away once you start using Julia more like how it was designed to be used (with functions that accept global variables as arguments). I went through the same transition and had many of the same struggles you are facing. @mkitti’s answer has the common workarounds. You can use let or global as quick fixes for your scripts, but the long-term solution is to starting thinking in terms of functions. If you use functions, then you don’t need to bother learning the complicated hard/soft scoping rules; the loops will work as you expect.

Some links:

6 Likes