Before using a variable in a formula, you
must declare it.
A variable can hold values of a given
type. The allowed types are the seven simple types (Number, Currency, String,
Boolean, Date, Time and DateTime), the six range types (Number Range, Currency
Range, String Range, Date Range, Time Range and DateTime Range) and variables
that hold arrays of the previously mentioned types. This gives a total of 26
different types that a variable can have.
When you declare a variable, you also
specify its name. A variable cannot have the same name as any function,
operator or other keyword that is valid for Crystal syntax. For example, your
variable cannot be named Sin, Mod or If because Sin is a built in function, Mod
is a built in operator and If is a built in keyword. When typing formulas on
the Formulas page, the names of the built in functions, operators and other
keywords are highlighted in a different color and so it is easy to check if the
variable name conflicts.
Once a variable is declared, it can be
used in the formula. For example, you might want to assign it an initial value:
Local NumberVar x; //Declare x to be a Number variable
x := 10; //Assign the value of 10 to x
Note: The keyword for
declaring the Number variable has a Var at the end. This is true for all the
variable types in Crystal syntax.
A variable can only hold values of one
type. For example, if a variable holds a Number value, you cannot later use it
to hold a String.
Example
Local StringVar y;
y := "hello";
//OK- the Length function expects a String argument
Length (y);
//Error- y can only hold String values
y := #Jan 5, 1993#;
//Error- y can only hold String values
y := ["a", "bb", "ccc"];
//Error- the Sin function expects a Number argument
Sin (y);
You can combine declaring a variable and
assigning it a value in a single expression. For example:
Local NumberVar x := 10 + 20;
Local StringVar y := "Hello" + " " + "World";
Local DateVar z := CDate (#Sept 20, 1999#);
Local NumberVar Range gradeA := 90 To 100;
This is a good practice because it is
more efficient and helps prevent the common mistake of having incorrectly
initialized variables.
Here are some more examples of declaring
and initializing range variables:
Local NumberVar Range gradeA;
Local DateVar Range quarter;
gradeA := 90 To 100;
quarter := CDate (1999, 10, 1) To CDate (1999, 12, 31);