Darwin Help

Back to Index

Local Variables

  The "local" statement in a procedure body, defines the variables which are local to the procedure. That is, variables that will only exist for each invocation of the procedure. The variables will not be assigned any value nor will retain any value after the procedure end its execution. Recursive invocations of a procedure will have their own set of local variables, distinct for every invocation. Normally it is not necessary to define any local variables, as any variable which is assigned in the body of the procedure (either explicitly or implicitly in a for-loop) will be made automatically local. To enforce that an assigned variable be global, it must be defined in the global statement (see global).

  Local variables will be accessible to any procedure which is defined inside the body of the procedure. This is normally called "lexically scoped variables". The following example clarifies the access rules for variables.

outer := proc( a:numeric )
  local x;
  x := a+w;
  inner := proc( b:numeric )
    y := x+b+z
  end:
  x+inner(7)
end:

  The above code defines a procedure called outer. This procedure has one formal parameter, "a". It also defines a local variable "x"; but this definition is redundant, as x is assigned inside outer and will automatically be defined local. "inner" is also a local variable of "outer" as it is assigned a values inside it. "inner" is a procedure which takes one argument, "b". "inner" will have a local variable, "y", which is assigned inside its body. The assignment inside "inner" illustrates all the types of access to variables: y is local, b is a parameter. Parameters and local have the highest binding, that is will dominate over other forms of reference. "x" is external to "inner" but local to "outer" where "inner" is defined to which it refers. So the "x" in "x+b+z" refers to the local "x" in outer. "x" is called a lexically scoped variable. It has the second binding strength. Finally, both "w" and "z" are neither parameters nor locals of any of the functions and hence are global.

See Also

global,   objectorientation,   procedure