📝Dynamic scoping

As opposed to lexical scoping, dynamic scoping traverses the current invocation stack to find free variables. (Lexical scoping traverses scopes defined by lexical structure of the program.)

Emacs Lisp is the most canonical language that uses dynamic scoping.

(defvar name "world")

(defun hello ()
  (princ (format "Hello, %s!\n" name)))

(let ((name "blah")) ; name is a local binding here
  (hello))

(hello)
Hello, blah!
Hello, world!

Another (more sane) example is Racket’s parameters.

#lang racket
(define name (make-parameter "world"))

(define (hello)
  (printf "Hello, ~a!\n" (name)))

(parameterize ([name "blah"])
  (hello))

(hello)
Hello, blah!
Hello, world!

See also:

Backlinks