help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Lexical and Dynamic Scope


From: Robert Thorpe
Subject: Lexical and Dynamic Scope
Date: Sat, 19 Jul 2014 21:06:48 +0100

Stefan Monnier <address@hidden> writes:

>> Because they can be encoded different things it makes sense calling
>> this lexical (because the value is simply read, not looked up) and not
>> "static".
>
> It's also called "static scoping".  And the name doesn't have much to do
> with the implementation technique used.  It's called "lexical" because
> the way a particular identifier use is matched to a particular variable
> only depends on the shape of the program text rather than depending on
> its run-time behavior.

I'll elaborate a bit....  What we're talking about here is where
variables are visible.  How those variables behave is a different
question.  They could only hold one type (classical static typing), hold
a set of types or hold any type ("dynamic" typing) depending on the
language.

Most languages have lexical scope.  The scope of a variable is defined
by a part of the program text.  For example, a variable Bar is defined
in a function Foo.  That means Bar is visible within Foo only.  The
section of text defines where variables can be accessed, that's why it's
called "lexical" or "static".  There can be multiple levels of lexical
scoping, for example in C some variables are visible everywhere in a
file.  One way of thinking about it is by thinking of a stack.  The
current lexical area and everything defined in it is the top of the
stack.  When the code exits that area that place on the stack disappears
(it's popped).  When a function call occurs a new entry on top of the
stack is created (a push).

Dynamic scope means that visibility follows code execution.  If a
variable Baz is defined by code executed in the past then it's visible
by present code.  If a local variable called Baz is defined then it's
used instead of the more global one.  The "higher level" value continues
to exist.  This can be thought of using stacks too, in a slightly
different way.  In the dynamic case there's a stack for every
*variable name*.  If a local variable is defined for a name that's
already used then a new value is pushed on the stack of variable values
and removed when the local area ends.

Stefan and the Emacs maintainers added lexical scope because it makes
Emacs Lisp faster and it's simpler to understand.

BR,
Rob



reply via email to

[Prev in Thread] Current Thread [Next in Thread]