Scope modifiers: Difference between revisions
Content added Content deleted
({{omit from|ZX Spectrum Basic}}) |
(→{{header|Common Lisp}}: Add example using (declaim (special *bug*)).) |
||
Line 107: | Line 107: | ||
The defining operators <code>defvar</code> and <code>defparameter</code> globally declare a variable special, though this can also be done using <code>declaim</code>. Local special declarations are rarely used. |
The defining operators <code>defvar</code> and <code>defparameter</code> globally declare a variable special, though this can also be done using <code>declaim</code>. Local special declarations are rarely used. |
||
The next example declaims that <code>*bug*</code> has dynamic scope. Meanwhile, <code>shape</code> has lexical scope. |
|||
[[Category:Common Lisp examples needing attention]] [This task should be expanded with some examples.] |
|||
<lang lisp>;; *bug* shall have a dynamic binding. |
|||
(declaim (special *bug*)) |
|||
(let ((shape "triangle") (*bug* "ant")) |
|||
(defun speak () |
|||
(format t "~% There is some ~A in my ~A!" *bug* shape)) |
|||
(format t "~%Put ~A in your ~A..." *bug* shape) |
|||
(speak)) |
|||
(let ((shape "circle") (*bug* "cockroach")) |
|||
(format t "~%Put ~A in your ~A..." *bug* shape) |
|||
(speak))</lang> |
|||
The global function <code>speak</code> tries to use both <code>*bug*</code> and <code>shape</code>. For lexical scope, the value comes from where the program ''defines'' <code>speak</code>. For dynamic scope, the value comes from where the program ''calls'' <code>speak</code>. So <code>speak</code> always uses the same "triangle", but can use a different bug. |
|||
<pre>Put ant in your triangle... |
|||
There is some ant in my triangle! |
|||
Put cockroach in your circle... |
|||
There is some cockroach in my triangle!</pre> |
|||
The stars around <code>*bug*</code> are only good style; they are no requirement of the language. Lispers like to put stars on special variables. |
|||
=={{header|E}}== |
=={{header|E}}== |