Declaration of script variables
Provides a reference for the syntax of script variable declarations in OPL.
| Syntax | Effect |
|---|---|
where
each has the form variable [ = expression ] |
Declares each script variable as a local variable. If an expression is provided, it is evaluated and its value is assigned to the variable as its initial value. Otherwise, the variable is set to the undefined value. Examples: var x var name
= "Joe" var average = (a+b)/2, sum, message="Hello" |
Inside a function definition
Script
variables declared with var are local to the function,
and they hide any global variables with the same names; they have
the same status as function arguments.
For example, in the following
program, the script variables sum and res are
local to the average function, as well as the arguments a and b ;
when average is called, the global variables with
the same names, if any, are temporarily hidden until exit from the
function:
function average(a, b) {
var sum = a+b
var res = sum/2
return res
}
Script variables declared with var at
any place in a function body have a scope which is the entire function
body. This is different from local variable scope in C or C++. For
example, in the following function, the variable res declared
in the first branch of the if statement is used in
the other branch and in the return statement:
function max(x, y) {
if (x > y) {
var res = x
} else {
res = y
}
return res
}
Outside a function definition
At the same level
as function definitions, script variables declared with var are
local to the current program unit. A program unit is a group of statements
which is considered a whole; the exact definition of a program unit
depends on the application in which the script is embedded. Typically,
a script file loaded by the application is treated as a program unit.
In this case, variables declared with var at the
file top level are local to this file, and they hide any global variables
with the same names.
For example, suppose that a file contains the following program:
var count = 0
function NextNumber() {
count = count+1
return count
}
When this file is loaded, the function NextNumber becomes
visible to the whole application, while count remains
local to the loaded program unit and is visible only inside it.
It
is an error to declare the same local variable twice in the same scope.
For example, the following program is incorrect because res is
declared twice:
function max(x, y) {
if (x > y) {
var res = x
} else {
var res = y // Error
}
return res
}