We will briefly examine dynamic scope, to hammer home the contrast. But, more important, dynamic scope actually is a near cousin to another mechanism (
As we saw in Chapter 2, lexical scope is the set of rules about how the engine can look up a variable and where it will find it. The key characteristic of lexical scope is that it is defined at author time, when the code is written (assuming you don’t cheat with
Dynamic scope seems to imply, and for good reason, that there’s a model whereby scope can be determined dynamically at runtime, rather than statically at author time. That is in fact the case. Let’s illustrate via code:
Lexical scope holds that the RHS reference to
foo() will be resolved to the global variable
a, which will result in value
2 being output.
Dynamic scope, by contrast, doesn’t concern itself with how and where functions and scopes are declared, but rather where they are called from. In other words, the scope chain is based on the call-stack, not the nesting of scopes in code.
foo() is executed, theoretically the code ...