Further Clarification on scoping rules

Sorry if I am overlooking something again. But according to the documentation on Scope:

Variables in outer scopes are visible from any scope they contain — meaning that they can be read and written in inner scopes — unless there is a local variable with the same name that "shadows" the outer variable of the same name.

When we say that a variable "exists" in a given scope, this means that a variable by that name exists in any of the scopes that the current scope is nested inside of, including the current one.

So I am confused why something like this returns an error

function dinner(A)
    eat()
end

function eat()
    println("eat $A")
end

dinner("Apple")
ERROR: UndefVarError: A not defined

Why isn’t the variable A as defined by dinner visible inside the function eat? It seems as though it would be given that eat is in the inner scope of dinner?

Moreover as functions introduce a hard scope where:

If x is not already a local variable and assignment occurs inside of any hard scope construct (i.e. within a let block, function or macro body, comprehension, or generator), a new local named x is created in the scope of the assignment;

A = "pear"
"pear"

dinner("apple")
eat pear 

I am uncertain why eat is overlooking the local variable A it is nested in, but accepting the global variable A. Would someone be able to clarify this point? My untutored reading of the documentation seems to indicate that the opposite would be true.

The scope of something depends on where that object is defined rather than where it is called. The function eat is defined in global scope, therefore it does not see the local variables of other functions (but it does see global variables).

If it were the other way around, chaos would ensue.

Another way to see the difference is to define a closure instead, which is a function defined in the local scope of another function:

function dinner(A)
  function eat()
    println("eat $A")
  end
  eat()
end
2 Likes

This is the difference between lexical scoping and dynamic scoping. There’s an interesting history of the two scoping rules you can read up on, aiui dynamic scoping was the earlier of the two.

3 Likes

oh wow…that clears up a lot of the confusion I’ve been having. Thanks so much guys!