Scope modifiers: Difference between revisions

Content added Content deleted
(→‎JavaScript: new example)
(→‎{{header|Common Lisp}}: Explain Lisp earmuffs more.)
Line 132: Line 132:
There is some cockroach in my triangle!</pre>
There is some cockroach in my triangle!</pre>


The stars around <code>*bug*</code> are called "earmuffs" and are not a special syntax. Rather, they are part of the symbol's name. This widely-used convention effectively places dynamic variables into their own namespace. If dynamic variables are not in their own namespace, then variables intended to be lexical may accidentally clash with dynamic variables of the same name. This is a problem in two ways: the dynamic variable is accidentally overridden which can change the behavior of code which depends on its value; furthermore, this variable is captured by lexical closures as the program expects: it refers to whatever dynamic value is in effect at the time the closure is called, and not the binding which existed when the closure was made.
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.

For similar reasons, earmuffs were used in earlier dialects of Lisp which had only dynamic variables. (One noteworthy surviving descendant dialect is Emacs Lisp.) Variables with earmuffs are intended to be global and occur as free references in code. Variables not denoted by earmuffs are intended to be local. They are always bound in the scope where they are used so their references do not escape (which could happen accidentally, and is usually a bug). An interpreter or compiler for such a dialect could implement checks to enforce this convention.

Common Lisp follows this tradition in its standard dynamic variables like <code>*print-circle*</code>, <code>*readtable*</code> et cetera. Furthermore, the idea of a pervasively special symbol further provides support for the programming style of the traditional dynamically scoped dialects. Programs from such a dialect can be ported to Common Lisp with little changes to how the variables are handled. The "earmuff" variables just have to be properly defined, and most non-earmuff variables can become lexicals.


=={{header|Delphi}}==
=={{header|Delphi}}==