|
|||||
Scope of variables | |||||
Prerequisite Concepts | Related Syntax |
A scope is a region of the program in which a particular set of variable names is visible. In general, you can declare new variables at the beginning of a scope, and these variables cease to be visible at the end of the scope.
There are two kinds of scopes, local and global.
A global scope encompasses the entire program. Variables declared in the global scope are visible in any part of the program. A global variable is one that has been declared using the global
keyword. For example:
global stream foo
Global variables can be declared anywhere in the program except within rules and function definitions.
A local scope encompasses a smaller portion of the program. Each rule body or function body is a complete local scope. Local variables are declared immediately after the rule header or function header, and are declared using the local
keyword. For example:
find "foo" local stream bar
OmniMark requires that local variable declarations appear at the beginning of the local scope. The local declarations must appear prior to any actions within that scope, and the local variables can only be used by the actions within that scope.
In addition to the local scopes created within rules and functions, all of the do
and repeat
actions encapsulate a local scope. For example, the following rule contains two local scopes, one nested within the other. The first local scope is that created by the rule, and the second is that which exists within the repeat over
block:
process local counter foo initial {0} repeat over quotes local stream bar set bar to quotes output quotes || "%n" increment foo again output "There were %d(foo) items on the shelf.%n"
The following are examples of local scopes:
repeat
or a repeat over
loop
match
alternative in the do scan
or repeat scan
control structures
else
alternative in a do when
, do unless
, do select
, or do scan
action
do...done
block
In the following example, the behavior of local variables within repeat...again
loops is demonstrated. The value of "temp" that is output is 1 for each iteration because the local scope is re-entered each time the loop is repeated and each iteration gets, in effect, its own "temp":
local counter k ... set k to 4 repeat local counter temp output "temp's value is %d(temp).%n" set temp to k decrement k exit when k = 0 again
Prerequisite Concepts Variables |
Related Syntax global, local |
---- |