Skip to content

Commit

Permalink
Add mention of lexical scoping in Variables and Scoping
Browse files Browse the repository at this point in the history
  • Loading branch information
nalimilan committed Dec 7, 2014
1 parent b83e4bb commit 5c04ee9
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions doc/manual/variables-and-scoping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,47 @@ Notably missing from this list are
Certain constructs introduce new variables into the current innermost
scope. When a variable is introduced into a scope, it is also inherited
by all inner scopes unless one of those inner scopes explicitly
overrides it. These constructs which introduce new variables into the
current scope are as follows:
overrides it.

Though, regarding the special case of functions, please note that Julia
uses `lexical scoping <https://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scoping_vs._dynamic_scoping>`_,
meaning that a function's scope does not inherit from its caller's
scope, but from the scope in which the function was defined. Thus,
functions do not have access to variables introduced in their caller
function's scope. For example, in the following code ``x`` is found
in the global scope (and if no global variable ``x`` existed, an
undefined variable error would be raised)::

function foo()
x
end

function bar()
x = 1
foo()
end

x = 2

julia> foo()
2

On the other hand, in the following example, the closure ``foo`` is
defined inside ``bar``, therefore it inherits from its scope::

function bar()
foo = () -> x
x = 1
foo()
end

x = 2

julia> bar()
1

These constructs which introduce new variables into the current scope
are as follows:

- A declaration ``local x`` or ``const x`` introduces a new local variable.
- A declaration ``global x`` makes ``x`` in the current scope and inner
Expand Down

0 comments on commit 5c04ee9

Please sign in to comment.