The manual's section on variable scope sucks

Agreed; eliminate them if you can. I’d prefer a rewrite where complexity is added as you go down the page, so a user can read as far as they are comfortable. A user should not need to understand every nuanced scope detail to run their first loop.

It runs fine in a let block or some other local scope, where the output is

0
10

But if the outer scope is global, I get one of the following:

0
0
0
...
10
10
10
...
ERROR: LoadError: UndefVarError: `i` not defined in local scope
Suggestion: check for an assignment to a local variable that shadows a global of the same name.

I emphasize the while case because I think this is where users are most likely to encounter their first scoping problem. I wrote loops like this all the time without thinking about it in Matlab.

@sadish-d’s main complaint seems to be that the scope manual is imprecise. My main complaint is that the scope manual is unapproachable. These are somewhat competing design philosophies. In a perfect world you would achieve both simultaneously, but you may need to focus different sections one way or another.

That said, I feel strongly both can co-exist in the same manual. My personal preference would be to switch the manual organization from:

# Topic A
if global
  if script
    rules
  end
  if interactive
    rules
  end
else
  rules
end

# Topic B
if ...

to

# Usually
## Explaination
Julia users are encouraged to write code inside functions where the following scoping rules apply.
## Topic A
rules
## Topic B
rules

# Scoping Changes for Global Variables
## Explaination
global variables behave differently because ... (across files, compiler performance)
## Topic A
rule changes
## Topic B
rule changes

# Scoping Changes for Interactive Sessions
## Explaination
the REPL and notebooks behave differently because ... (convenience trumps performance)
## Topic A
rule changes
## Topic B
rule changes

I think this gives you the best shot of being precise and accessible simultaneously.

1 Like