1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
<HTML>
<HEAD>
<TITLE>Common LISP Hints: Dynamic Scoping</TITLE>
</HEAD>
<BODY>
<A HREF="LISP-tutorial-11.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-13.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc12"><IMG SRC="toc.gif" ALT="Contents"></A>
<HR>
<H2><A NAME="s12">12. Dynamic Scoping</A></H2>
<P>The <CODE>let</CODE> and <CODE>let*</CODE> forms provide lexical scoping, which is what you
expect if you're used to programming in C or Pascal. Dynamic scoping is
what you get in BASIC: if you assign a value to a dynamically scoped
variable, every mention of that variable returns that value until you
assign another value to the same variable.</P>
<P>In LISP, dynamically scoped variables are called <EM>special variables</EM>. You
can declare a special variable with the defvar special form. Here are
some examples of lexically and dynamically scoped variables.</P>
<P>In this example, the function <CODE>check-regular</CODE> references a regular (ie,
lexically scoped) variable. Since <CODE>check-regular</CODE> is lexically outside of
the <CODE>let</CODE> which binds <CODE>regular</CODE>, <CODE>check-regular</CODE> returns the
variable's global value.</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (set 'regular 5) ;setq would make it special in CMUCL!
5
> (defun check-regular () regular)
CHECK-REGULAR
> (check-regular)
5
> (let ((regular 6)) (check-regular))
5
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>In this example, the function <CODE>check-special</CODE> references a special (ie,
dynamically scoped) variable. Since the call to <CODE>check-special</CODE> is
temporally inside of the <CODE>let</CODE> which binds special,
<CODE>check-special</CODE> returns
the variable's local value.</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (defvar *special* 5)
*SPECIAL*
> (defun check-special () *special*)
CHECK-SPECIAL
> (check-special)
5
> (let ((*special* 6)) (check-special))
6
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>By convention, the name of a special variable begins and ends with a *.
Special variables are chiefly used as global variables, since
programmers usually expect lexical scoping for local variables and
dynamic scoping for global variables.</P>
<P>For more information on the difference between lexical and dynamic
scoping, see <EM>Common LISP: the Language</EM>.</P>
<HR>
<A HREF="LISP-tutorial-11.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-13.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc12"><IMG SRC="toc.gif" ALT="Contents"></A>
</BODY>
</HTML>
|