On this page:
3.1 Dynamic Scope by Default
3.2 Dynamic Scope as a Feature

3 Dynamic Scope in Programming Languages

How do major programming languages deal with scope?

3.1 Dynamic Scope by Default

Lisp originally introduced dynamic scoping (accidentally). While Scheme was originally created as a variant of Lisp with lexical scoping (among other differences), most recent versions adopt lexical scoping by default (see next section). However, some variants of Lisp still rely on dynamic scope, the most popular of which being Emacs Lisp.

Other languages also stick to dynamic scope. I’m not sure whether it’s on purpose or accidental! Examples include TeX, and bash’s local form.

Question: Write a small bash script that illustrates that local has dynamic scope.

3.2 Dynamic Scope as a Feature

Most programming languages embrace lexical scope as the default, yet provide dynamic scope as an opt-in feature. Below are some well-known examples (click to go to some related documentation):

Some languages do not explicitly provide a dynamic scoping mechanism, but provide a lower-level mechanism for thread-local storage, which can be used to implement dynamic variables. Thread-local storage addresses the issue with shared mutable state discussed previously. For example, see thread locals in Java.

Question: What about your favorite language? Does it embrace dynamic scope by default? If not, does it support some mechanism similar to those mentioned above?