|
| |
Functions, Arrays, and Program Flow
Note: In syntax definitions, italics means that is something to be filled in,
"[]" mean that it is optional, and "..." mean that there can be more
than one.
Before you continue with this chapter, it might be beneficial to quickly look over the glossary.
To declare variables, you use the Dim keyword. The syntax for Dim is the
following:
You can declare multiple variables with Dim by separating them with commas.
Dim indentifier1, identifier2, identifier3 ...
An identifier starts with a letter, and then can contain up to 254 characters.
Generally it is a good idea to stick to letters, numbers, and underscores, but some other
punctuation marks are allowed. Certain words cannot be used for identifiers, as they
are used by VBScript. These are called reserved words. Dim is
optional in most cases (but not all), since the browser will define the variable when you
first use it.
To set a value to a variable, you use the = operator. It is used for two things,
comparison and assigning values. For example:
Dim x
x = 8
If x = 8 Then Alert "X is 8"
x = x + 9
This example defines X as a variable, sets the value 8, shows a message if X is equal
to 8, and then adds 9 to the current value of X. Note that a variable can be used on
both sides of the = operator.
A subroutine is easy to define. All you do is follow this syntax:
Sub identifier([parameter list])
*** VBScript Code Here ***
End Sub
All lines of code between the Sub and the End Sub will be executed whenever the
subroutine is called. The parameter list is optional. It is a list of
identifiers, separated by commas. After the function syntax will be an example.
Function identifier([parameter list])
*** VBScript Code Here ***
End Function
Notice the similarities. The only difference is that Sub is replaced by Function.
However, it is expected that in the function body (the "code here"
section), you will return a value. You do this by using the function name in an
assignment statement. For example:
Function Squared(aNumber)
Squared = aNumber * aNumber
End Function
(The asterisk is the VBScript operator for multiplication.)
All variables in VBScript are variants. They can hold one type of data in one
place in the script, and another later on. This code is valid:
Dim X
X = 5
X = "Hello"
X = 8.35
X = True
X = Date()
Many programming languages have variables which must be only one type, like integer,
string, decimal, etc., but VBScript isn't like that. Thus, in some cases, it is
necessary to use built-in conversion functions so that data is interpreted as the correct
type. Some conversion functions are CStr (to string), CSng (to floating point,
single precision) and CInt (to integer).
Arrays are also defined with Dim. Here is the syntax to declare an array.
Dim identifier([subscript1, subscript2 ...])
From 0 to 60 subscripts are supported, though if you use 0 subscripts, you will have to
use ReDim, which is discussed next, before you can use the array. ReDim
changes the size of the array, so that is stores more or less data. The subscript is
one less than the number of items in the array, since the array always starts at 0.
ReDim [Preserve] identifier(subscript1, subscript2 ...)
If used, Preserve saves the data currently in the array. Otherwise, the array is
emptied. If you ReDim the array to make it smaller, data in the portion removed will
always be lost.
Here is an example:
Dim AnArray(5)
AnArray(3) = "Hello"
ReDim Preserve AnArray(4)
ReDim AnArray(9, 2)
AnArray(3,5) = "Goodbye"
ReDim Preserve AnArray(3, 1)
Whenever you use the Dim statement to declare a variable or array, the values are
filled with either a 0 (if it's a number) or an empty string. This is called
initialization.
Where you place the Dim statement is very important regardless of whether you are using
it to declare a variable or array. The placement of the Dim statement determines
where the variable or array can be used (the scope). If you put the Dim statement in
a Script tag, but not in a subroutine or function, it is declared 'globally', meaning that
you can use that variable in any function or subroutine on the page. If you put the
Dim statement in a function, it can only be used in that function, as with subroutines.
<SCRIPT TYPE="text/vbscript" LANGUAGE="VBScript">
<!--
Dim X
Sub Test1()
Dim Y
Y = 30
End Sub
Sub Test2()
Alert X + Y
End Sub
Test1
Test2
'-->
</SCRIPT>
To make your coding easier to understand and to make it easier to notice typos, you can
put Option Explicit at the beginning of each Script tag,
right after the start of the comment tag. This causes a message to be displayed by
the browser whenever a variable isn't declared using Dim.
In Chapter 1, two methods of putting script code into an
HTML document were discussed, both for event handlers. There is another way of
writing event handlers, which is writing a subroutine. The subroutine's name is
composed of the object's ID/name, followed by an underscore and the event. For the
button Button1, you would handle a click event like this:
<SCRIPT TYPE="text/vbscript" LANGUAGE="VBScript">
<!--
Sub Button1_OnClick()
Alert "This is a message.", vbExclamation, _
"VBScript Test"
End Sub
'-->
</SCRIPT>
This is much easier than enclosing all the script code inside the object tag, and is
more compatible with current browsers than using the For and Event attributes of the
Script tag. This also allows all event handlers to be put together in one script
tag, so that they are easier to find and reuse.
By now, you may have guessed what the final method of writing VBScript in HTML is.
It is writing code directly within a Script tag. Any statements in a Script
tag but not in a subroutine or function are run when the browser reaches that point in the
page. This allows you to add content to the middle of a page easily.
The ampersand ("&") is used in VBScript to attach two strings.
<SCRIPT TYPE="text/vbscript" LANGUAGE="VBScript">
<!--
Document.Write "This page was updated " & _
Document.LastModified & ".<BR>"
Document.Write "It was " & Time() & _
" when you loaded this page."
'-->
</SCRIPT>
Below is what the above script would output.
Boolean values are either true or false. Internally, VBScript always uses -1 for
true and 0 for false, though when it is converting numbers to boolean values, all non-zero
numbers are true. Other than converting number to boolean values, you can also get
boolean values by using comparison operators or logical operators.
| Comparison Operator |
Function |
Logical Operator |
Function |
| val1 = val2 |
True if they are the same |
val1 And val2 |
True if both are true |
| val1 <> val2 |
True if they are not the same |
val1 Or val2 |
True if one or both are true |
| val1 < val2 |
True if val1 is less than val2 |
Not val |
True if val is false |
| val1 > val2 |
True if val1 is greater than val2 |
val1 Xor val2 |
True if only one is true |
| val1 <= val2 |
True if val1 is either less than or the same as val2 |
val1 Eqv val2 |
True if both are true or both are false |
| val1 >= val2 |
True if val1 is either greater than or the same as val2 |
val1 Imp val2 |
True if val2 is true or both are false |
Conditional statements allow you to make a section of code dependant on something else.
There are four types of conditional statements in VBScript, three of which use boolean
conditions.
In the syntax definitions, statements can be any type of VBScript statement.
- If condition Then statement [Else statement]
- If condition Then
statement(s)
[Else
statement(s)]
End If
- If condition Then
statement(s)
ElseIf condition
statement(s)
ElseIf condition
statement(s)
ElseIf condition
statement(s)
...
End If
- Select Case expression
Case value
statement(s)
Case value
statement(s)
Case value
statement(s)
...
[Case Else
statement(s)]
End Select
The first conditional statement is best suited for situations where you only want to
perform one action if the condition is true, and possibly one if it is false. Ex:
If UserName = "George" Then Alert "Hi, George." Else Alert
"You're not George."
The second conditional statement is best suited for situations where you want to
perform one or more actions if the condition is true, and possibly one or more actions if
it is not.
The third conditional statement is best suited for situations where there are many
conditions, and depending on them, you want to take certain actions.
The fourth conditional statement is the oddball. For Expression, you give
anything that evaluates to a single value. For each Value, , you provide a value,
such as a string, a number, or boolean value. It chooses one of the groups of
statements after a Case Value pair by comparing the expression to the values. Ex:
Dim aVar
Randomize
aVar = Int(3 * Rnd + 1)
Select Case aVar
Case 1
Alert "You got a one."
Case 2
Alert "You got a two."
Case Else
Alert "You got something other than a one
or two."
End Select
Looping structures are used to repeat a section of code, without having to write it
multiple times. Here, two looping structures will be covered. Together, these
two can be used to fill any need for looping. There are other looping structures
which are covered in the MS VBScript
Reference.
- For indexval = start To finish [Step stepval]
statement(s)
Next
- Do While condition
statement(s)
Loop
The For loop is best used when you know how many times it should loop. The
Indexval is any variable. When the loop is entered, it becomes equal to Start.
Each time it reaches the Next, it changes the value of Indexval by either Stepval,
or one if Stepval is not specified, until it is past Finish. For loops can be used very
efficiently on arrays. Ex:
Dim x
For x = 3 To 0 Step -1
If x > 0 Then
Alert x
Else
Alert "BlastOff!"
End If
Next
Dim y (3)
For x = 0 To 3
y(x) = (x + 1) * 3
Alert y(x)
Next
The Do loops (there are more than one) are best used when you don't know how many times
it should loop, such as when reading in from a file which contains an unknown amount of
data. The Do While loop executes the statements as long as the Condition is True.
If, when it gets to the Do statement, the condition is False, it will not execute
the statements at all. It is important to be careful when making loops, because if
the value of the Condition doesn't change within the loop's statements, the loop will
never stop. Ex:
Function RandomString(len)
Dim lenCount
Dim tmpString
Dim tmpChar
Randomize 'Insure that the numbers are really random
lenCount = 0
Do While lenCount < len
tmpChar = Chr(Int(75 * Rnd + 48))
'Random characters (letters, numbers, etc.)
tmpString = tmpString & tmpChar
'Add the character to the string
lenCount = lenCount + 1 'Increase the counter
Loop
RandomString = tmpString 'Return the string
End Function
If you're thinking that this could also be done with a For loop, you're right. In
many instances, it is personal preference which determines which looping structure to use.
|