From CS 61A Wiki
Revision as of 11:32, 9 July 2014 by Dickson.tsai (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Jump to: navigation, search

An environment consists of a sequence of frames. Code is evaluated line by line in the environment. Starting in the global frame, users evaluate environments by binding values to variables and by evaluating function calls. Function calls will create local frames, in which the user evaluates the calls (like a mini environment) and returns to the global frame. One way to evaluate an environment is through environment diagrams.


Text Example

In the following code, the sequence of frames that makes up the environment of inner is innerouterglobal.

x = 1
y = 2
def outer():
    x = 3
    y = 4
    def inner():
        x = 5
        y = 6
    return inner

  1. The integer 1 is assigned to variable x.
  2. 2 is assigned to y.
  3. The variable outer points to a function.
  4. The interpreter moves down to outer()(), and executes the function outer().
    1. x and y are re-assigned to 3 and 4 respectively.
    2. The variable inner points to a function (do not execute this function yet!).
    3. "Return inner" indicates that outer() returns the function inner.
  5. Since outer() returns inner, now we execute what's left: inner().
    1. x and y are re-assigned to 5, 6.
  6. Program terminates.

Visual Example

See also