Dynamic scoping is a method of variable scoping where variables are bound based upon the call stack, instead of where they are defined.
Dynamic scoping is a method for determining variable scope which uses the call-stack to figure out which value an unbound variable (a variable which is defined outside the currently executing function) should have. Dynamically scoped languages will look up the call stack (first the caller, than the caller's caller, and so on) to find unbound variables.
The more popular method of scoping, lexical scoping (alternatively, static scoping), uses the program source code to figure out how to place scopes. For example, consider the following Python code:
def increment_by(x):
def inner(y):
return x + y
return inner
def main():
add_two = increment_by(2)
x = 12
print(add_two(12))
main()
As output, this program will produce the number 14; this is because, when Python sees the unbound name called x
, it looks to see how it was defined in the function increment_by
, since inner
was defined inside increment_by
in the program source code. When increment_by
was executed to produce the inner
function, x
was equal to 2, so Python uses the value 2 for the variable x
inside inner
.
However, the language Emacs Lisp is dynamically scoped, unlike Python - the equivalent code in Elisp is:
(defun increment-by (x)
;; This is actually the function called inner, but without a name
(lambda (y) (+ x y)))
(defun main ()
(let ((add-two (increment-by 2))
(x 12))
(funcall add-two 10)))
(main)
When run inside Emacs, the above code will return the value 22; this is because, when Elisp sees the unbound name called x
, it will look to see what value the caller gave x
. Since main
calls increment-by
, Elisp sees that main
defined x
to be 12, and thus uses the value 12 for x
.
Typically, this tag is meant to denote questions about dynamic scoping and how it affects programming in dynamically scoped languages.