>  The rule is that inside a function any variable assignment
> which would write to a *global* variable, makes that variable local. 
>
> I guess I still don’t understand how the nested function scoping behavior 
> is described by the above sentence. Maybe I don’t understand what you mean 
> by *global* and how I could determine if an assignment “would write to a 
> *global* variable”. My best attempt at describing this behavior in my own 
> way would be as follows: the assignment x = repmat(y.', 2, 1) within mesh 
> within foo treats x as “local-to-foo” and “global-to-mesh”. Is this 
> consistent with what your saying?

Have you read the whole of the scope-section? ;-)  There is one
subsection on global scope, so hopefully that clears what global scope
is, if not please let me know.  So defining `mesh` at the REPL prompt:

mesh(y) = (x = repmat(y.', 2, 1); return x)

means that x inside mesh will be local as it is assigned to.  However if
mesh gets nested inside a function which itself has a local x:

function foo()
   x = 1 # assignment makes it implicitly local
   mesh(y) = (x = repmat(y.', 2, 1); return x)
   mesh(5)
   return x
end

then the x inside mesh will refer to the *local* x.  If foo does not
define an x then mesh has its own x

function foo()
   xx = 1
   mesh(y) = (x = repmat(y.', 2, 1); return x)
   mesh(5)
   return xx
end

> Question 2) What advantage is there for changing the scoping rules for 
> nested functions? I did notice the following example in your manual but it 
> is not clear to me how it (or if it was intended to) explain the usefulness 
> of different scoping rules for nested functions.
>
> even(n) = n == 0 ? true  :  odd(n-1)
> odd(n)  = n == 0 ? false : even(n-1)
>
> julia> even(3)
> false
>
> julia> odd(3)
> true

No, in this example there are no nested functions, so above local vs
global does not apply.  This example is about being able to refer to
variables inside functions which are only defined later.

The reason for the hard-scope rule is to allow to make closures which
have their private state which cannot be access from outside:

let
    private_state = 0
    global foo
    foo() = (private_state +=1; private_state)
end

Calling foo will produce the natural numbers without anyone being able
to access the private_state directly.  This is different to

private_state = 0
foo() = (global private_state +=1; private_state)

where private_state is a global and can be accessed by anyone (although
only written to module locally).  I will add something about this to the
manual.

(PS: My statement "rewrote the scope section" should have read "updated
the scope section" as it still contains lots of the original text.  No
offence meant to the original authors.)

Reply via email to