When you start a RLaB session, either interactively or in batch-mode, you create an environment. The environment or workspace consists of the built-in functions, and any other variables or functions you may have added. The workspace will also be referred to as the global-symbol-table or the global scope.
There are two other types of environment available: a function's local environment and a file's static environment11
A function's local scope is temporary, it is created when the function is invoked, and is destroyed when the function returns. A file's static scope is created when the file is loaded, and remains intact until the RLaB session is terminated.
The different scopes serve to protect data from operations that occur in the other scopes. There is some degree of overlap in order to allow flexibility. Functions can affect file-static and global scopes; statements within files can affect statements within other files and the global scope. More simply put, the "lower" scopes generally have access to the "higher" scopes. When a variable is used, RLaB uses certain rules to "bind" the variable. When we use the term bind or bound, we mean that the variable name is associated with an entry in one of the three types of symbol tables.
There are exceptions: variables used in a function context are bound to the global-symbol-table. For example:
x = a * sin ( pi )
sin
is used in a function context, and is bound to the
global scope, while x
, a
, and pi
are
bound to the function's local environment.
Function's that are defined within a file have full access to the file's static variables. Function variables will be bound to the file's scope before local binding occurs.
---- beginning of file.r ---- static (A, pi) pi = atan(1)*4; fun = function ( a ) { return A*sin(pi*A*a); } ---- end of file.r ----
When `fun' is created it binds `A' and `pi' to file.r's static environment.
There are two declarations: `global' and `local' that can be used to override the default behavior if necessary. Variables declared local will be bound to the function's local scope, and variable declared global will be bound to the global scope.