Windows NT Internet and Intranet Development

To learn more about author Sanjaya Hettihewa, please visit the author's homepage.

Previous chapterNext chapterContents


- 15 -

Working with Data Structures


Data structures are the building blocks of VBScript applications because they hold all the information a VBScript application needs. Unlike some other programming languages, VBScript stores all data in a data type called Variant. A variable of Variant data type can store many different kinds of information, such as strings of characters (Hello), numbers (123), Boolean values (TRUE), and so on. To accommodate the need to store different kinds of data, the Variant data type consists of several data subtypes. The return data type of all VBScript functions is Variant. This chapter covers how VBScript applications store and manipulate data that belongs to subtypes of Variant (see Table 15.1 to learn about subtypes of Variant). A brief description of each subtype, as well as its range (when applicable), is provided in the table.

Table 15.1. Subtypes of Variant.

Subtype Description Range
Boolean A Boolean value TRUE or FALSE
Byte A byte value An integer between 0 and 255
Date A date A date between January 1, 100 and December 31, 9999
Double A double-precision A number between floating-point number -1.79769313486232E308 and 4.94065645841247E-324 for negative numbers, and a number between 4.94065645841247E-324 and 1.79769313486232E308 for positive numbers
Empty An uninitialized value 0 for numeric variables, "" (empty string) for string variables
Error An error code N/A
Integer An integer value An integer between -32,768 and 32,767
Long Relatively large values An integer between -2,147,483,648 and intege 2,147,483,647
Null Empty variable--does not contain any value N/A
Object An OLE automation object N/A
Single A single-precision A number between -3.402823E38 and floating point number -1.401298E-45 for negative values, and a number between 1.401298E-45 and 3.402823E38 for positive values
String Time A string of characters Up to about 2 billion characters in length. Atime between January 1, 100, and December 31, 9999
See Chapter 17, "Data Conversion and Validation," to learn how to convert data of one subtype to another subtype.


Note:VBScript examples in this chapter can be found in the CD-ROM kit that accompanies this resource library. Please browse the directory /Chap-15 for source code of examples to become familiar with how the examples function.

Data Structures

VBScript data structures can be broken into two categories--scalar data structures (also called scalar variables) and multi-dimensional data structures (also called array variables). Scalar variables generally hold a single data value, such as a number, a string of characters, or the date and time. See Figure 15.1 for an illustration of a scalar variable. As you can see, a scalar variable consists of only one data value--array variables, on the other hand, contain many data values.

Figure 15.1. A scalar data structure.

Arrays are useful when data is stored and accessed sequentially. Arrays are especially ideal for performing the same set of operations on a series of data locations. The most simple nonscalar data type is a single-dimensional array. A single dimensional array only has one index to data storage locations.

Multidimensional data structures have two or more indexes to data storage locations. Think of a multidimensional data structure as a spreadsheet worksheet. A spreadsheet worksheet has two dimensions--rows and columns. See Figure 15.2 for a two-dimensional data structure. The variable name alone is not sufficient for determining the value of a two-dimensional variable. The row and column of the data field is also needed.

Figure 15.2. A two-dimensional structure.

A multidimensional VBScript data structure can contain many additional dimensions for storing data. Figure 15.3 illustrates a three-dimensional VBScript data structure. Notice how the row, column, and height of the data storage location are required to store or retrieve data from a three-dimensional data structure.

Figure 15.3. A three- dimensional structure.

Generally, you should avoid using more than three dimensions in a data structure. Higher dimensions require large amounts of memory, and make the task of programming significantly harder. This is simply because it is difficult for the programmer to visualize data structures that contain more than three dimensions.

Data Structure Manipulation Functions

VBScript includes several functions for manipulating data structures. Before discussing how data structures are created and manipulated in a VBScript application, let's explore the functions provided by the VBScript language to manipulate data structures. Use the following functions to define and manage data structures in your VBScript applications. In the sections "Scalar Data Structures" and "Multidimensional Data Structures," you will learn how to use the Dim, Redim, Private, Public, IsArray, LBound, and UBound functions to create and manage VBScript data structures.

The Dim Statement

The Dim statement is used to declare variables, such as arrays, and assign them storage space. When numeric variables are declared with Dim, they are initialized with the value 0. Otherwise, they are assigned an empty string. The Dim statement can be used to declare several types of variables.

The ReDim Statement

If you are unsure about the size of an array when it is first declared, VBScript allows the creation of dynamic arrays. Dynamic arrays can be expanded or reduced as needed. Dynamic arrays can be created using the following syntax:

Dim <NameOfArray>()

Storage space for additional elements can be allocated for a dynamic array using the ReDim statement, as shown in the following syntax (simply indicate, in parentheses, the number of elements the array should have):

ReDim <NameOfArray>(10)

As an added advantage, VBScript dynamic arrays can be expanded while preserving existing array values. This is done by adding a Preserve keyword between the ReDim statement and the array name, like so:

ReDim Preserve <NameOfArray>(20)


Warning: If a data type was defined for a dynamic array using the As statement, the array's data type cannot be changed using the ReDim statement. Also, if a dynamic array is reduced in size using the ReDim statement, any data stored in the portion of the array that was deleted is permanently lost.

The Private Statement

By preceding a variable declaration with the Private keyword, you can limit the variable's scope to the script in which it was declared.

The Public Statement

By preceding a variable declaration with the Public keyword, the scope of a variable can be extended to other scripts.

The IsArray Statement

Returns TRUE if a data structure is an array and FALSE otherwise.

The Erase Statement

The Erase statement is used to free memory used by dynamic arrays and to reinitialize elements of static arrays. If the array is a dynamic array, all space taken up by the array is freed. Dynamic arrays then need to be reallocated, using the ReDim statement, before they can be used again. If the array is a static array, all array elements are initialized with 0 if its elements are numeric. However, the array's elements are initialized with empty strings if the elements are non-numeric. The syntax is as follows:

Erase <NameOfArray>

The LBound Statement

LBound can be used to determine the minimum index of an array dimension. For example, if ArrayVariable is a three-dimensional array defined with the statement Dim ArrayVariable(5 To 100, 10 To 200, 20 To 300), LBound(ArrayVariable,1) returns 5, LBound(ArrayVariable,2) returns 10, and LBound(ArrayVariable,3) returns 20.

The UBound Statement

UBound can be used to determine the maximum size of an array dimension. For example, if ArrayVariable is a three-dimensional array defined with the statement Dim ArrayVariable(100,200,300), UBound(ArrayVariable,1) returns 100, UBound(ArrayVariable,2) returns 200, and UBound(ArrayVariable,3) returns 300.

Scalar Data Structures

Virtually all subtypes of Variant are scalar data structures. A scalar data structure is declared using the keyword Dim and following it with the name of the variable. A variable name can contain letters, numbers, and underscore (_) characters. However, there are a few restrictions:


Tip: Give variables descriptive names. The variable name RowCount is far more descriptive than X2.

See Listing 15.1 for an example of how a scalar data structure is declared and used in a VBScript application. Line 3 of Listing 15.1 declares a scalar data structure named ThisIsAScalarVariable. Line 5 assigns it the value 5, line 6 adds 5 to it, and line 7 displays the value of ThisIsAScalarVariable in a message box (as shown in Figure 15.4).

Listing 15.1. Declaring and using a scalar data structure in a VBScript application (\Chap-15\Scalar.html).

 1: <SCRIPT LANGUAGE="VBScript">
 2:
 3: Dim ThisIsAScalarVariable
 4:
 5: ThisIsAScalarVariable = 5
 6: ThisIsAScalarVariable = ThisIsAScalarVariable + 5
 7: Msgbox "The value of ThisIsAScalarVariable is " & _
 8:        ThisIsAScalarVariable
 9:
10: </SCRIPT>

Figure 15.4. Value of the variable ThisIsA ScalarVariable.


Multidimensional Data Structures

Multidimensional data structures are used to store several data values in a single variable. A value known as an index is used to refer to individual data fields of a multidimensional data structure.


Note:A multidimensional data structure in VBScript can contain as many as 60 dimensions. Avoid using more than 3 or 4 dimensions because the complexity of your source code will skyrocket when you use more than 4 dimensions--not to mention the amount of RAM required to create the data structure.

Types of Multidimensional Data Structures

There are two main types of arrays: static arrays and dynamic arrays. Static arrays and dynamic arrays are very similar when it comes to storing and accessing data. However, the size of static arrays does not change while the program is being executed, unlike the size of dynamic arrays, which can be changed dynamically during program execution. Use static arrays whenever you are certain about the size of the array, and use dynamic arrays when you have no way of knowing the size of an array until execution time. For example, a spreadsheet application is of little use to anyone if it is implemented with a static array and therefore has a fixed spreadsheet size. A dynamic array is used in a spreadsheet application to dynamically change the size of the spreadsheet as data is inserted and deleted.


Note:In VBScript, the index of multidimensional data structures begins at 0. This means that the data structure declared using the VBScript statement Dim Array(20) actually contains 21 data fields.

Static Arrays

Static arrays are declared using the Dim keyword. Listing 15.2 demonstrates how a one-dimensional array containing six elements is declared.


Note:The following examples apply both to one-dimensional and multidimensional arrays. The only difference is that multidimensional arrays contain multiple indexes, each separated from the others with a comma. In the case of a two-dimensional array, the first value is the row index and the second value is the column index. For example, ArrayVariable(2,3) refers to the data stored in the second row and third column of the ArrayVariable data structure.

Listing 15.2. Declaring an array.

<SCRIPT LANGUAGE="VBScript">
<!--
  Dim VariableName(5)
-->
</SCRIPT> 

Values are assigned to VariableName using the index of the data field. Listing 15.3 demonstrates how to assign twice the value of each array index to data fields of the variable declared in Listing 15.2. For example, the data field 1 is assigned the value 2, the data field 2 is assigned the value 4, and so on.

Listing 15.3. Assigning values to an array.

<SCRIPT LANGUAGE="VBScript">
<!--
  VariableName(0) = 0
  VariableName(1) = 2
  VariableName(2) = 4
  VariableName(3) = 6
  VariableName(4) = 8
-->
<SCRIPT>

Values of array elements can be accessed by including the array index in parentheses following the name of the array. For example, Listing 15.4 demonstrates how to display the value of the array declared in Listing 15.2 whose index is 4.

Listing 15.4. Retrieving values from an array.

<SCRIPT LANGUAGE="VBScript">
<!--
Msgbox "Value of element = " & VariableName(4)
-->
<SCRIPT

Dynamic Arrays

Dynamic arrays are declared in much the same way as static arrays. The only difference is that no array size is specified at the time of the array declaration. The VBScript keywords Dim and ReDim are used to declare dynamic arrays, as demonstrated in Listing 15.5.

Listing 15.5. Declaring a dynamic array.

<SCRIPT LANGUAGE="VBScript">
<!--
  ReDim ArrayName()
  Dim   SecondArrayName()
-->
<SCRIPT

The ReDim keyword is used to modify the size of a dynamic array. Listing 15.6 demonstrates how to set the size (15 storage locations) of the variable ArrayName, which was declared in Listing 15.5.

Listing 15.6. Resizing a dynamic array.

<SCRIPT LANGUAGE="VBScript">
<!--
  ReDim ArrayName(15)
-->
<SCRIPT

The ReDim keyword can be used as many times as necessary to modify the size of an array. Listing 15.7 demonstrates how the ReDim statement is used to modify the size (increased to 25 storage locations) of the variable ArrayName, which was declared in Listing 15.6 with 15. The keyword Preserve is preceded by the variable name to ensure that the data of the array ArrayName is not lost when the array is resized.


Warning: Data will be lost when you reduce the size of an array--even if the Preserve keyword is used.

Listing 15.7. Resizing a dynamic array while preserving its data.

<SCRIPT LANGUAGE="VBScript">
<!--
  ReDim Preserve ArrayName(25)
-->
<SCRIPT


Warning: When the size of a dynamic array is reduced, the data contained in the reduced portion of the array is permanently lost.

Understanding Variable Scopes

It is important that you fully understand the concept of variable scope before developing VBScript applications. Failure to do so can result in applications with bugs that are hard to detect and fix.

You might be asking yourself, "What are variable scopes and what do they do for me?" Variable scopes define which subroutines of an application have access to the data stored in a variable. When developing VBScript applications, do not depend on global variables. Global variables defined at the application level and all subroutines of an application have access to global variables. On the other hand, local variables are accessible only to the subroutine in which the variable is declared. The use of local variables also increases the portability of subroutines. When a subroutine is dependent on a globally declared variable, it is not very portable.

Although it might seem complicated at first, the concept of variable scope is very simple. If a variable is declared in a subroutine, that variable is only accessible within that subroutine. On the other hand, if a variable is declared at the same level as subroutines of an application, that variable is accessible throughout the application. Such a variable is called a global variable because it is accessible throughout the application. The only time global variables are not accessible throughout the application is a special case known as local variable precedence. Local variable precedence occurs when a local variable is declared with the same name as a global variable. The following example demonstrates how variable scopes are used in VBScript applications.

The variable scope layout of the application in Listing 15.8 is given in Figure 15.5. Refer to Figure 15.5 while manually stepping through the application in Listing 15.9, taking into account how variable scopes function (as explained in the preceding paragraph). While manually stepping through the application, fill in the values at the end of each line of Listing 15.8. If you understand variable scope rules correctly, the values you enter in Listing 15.8 will look similar to the values of Listing 15.10. See Figure 15.6 for the output of the application in Listing 15.9.

Figure 15.5. Scope layout of the variables declared in Listing 15.9.

Listing 15.8. Fill in values of the variables at each point of execution.

Value of variable A in subroutine A = ____
Value of variable B in subroutine A = ____
Value of variable A in subroutine B = ____
Value of variable B in subroutine B = ____
Value of variable A outside subroutine A and B = ____
Value of variable B outside subroutine A and B = ____

Listing 15.9. Working with the scope of data structures (\Chap-15\Scope.html).

 1: <HTML>
 2: <HEAD>
 3:
 4: <TITLE>Working With The Scope Of Data Structures</TITLE>
 5: </HEAD>
 6: <BODY BGCOLOR=FFFFFF>
 7:
 8:     <SCRIPT LANGUAGE="VBScript">
 9:     <!--
10:
11:       Dim A
12:       Dim B
13:
14: ` =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
15:
16:       Sub SubroutineA ()
17:
18:       Dim A
19:       Dim B
20:
21:       A = 20
22:       B = 30
23:
24:       document.write "Value of variable A in subroutine A =  " _
25:                      & A & "<BR>"
26:       document.write "Value of variable B in subroutine A =  " _
27:                      & B & "<BR>"
28:
29:       End Sub
30:
31: ` =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
32:
33:       Sub SubroutineB ()
34:
35:       Dim A
36:
37:       A = 35
38:
39:       document.write "Value of variable A in subroutine B =  " _
40:                      & A & "<BR>"
41:       document.write "Value of variable B in subroutine B =  " _
42:                      & B & "<BR>"
43:
44:       End Sub
45:
46: ` =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
47:
48:       A = 5
49:       B = 10
50:
51:       Call SubroutineA
52:       Call SubroutineB
53:
54:       document.write "Value of variable A outside subroutine _
55:                      & A and B =  " & A & "<BR>"
56:       document.write "Value of variable B outside subroutine _
57:                      & A and B = " & B & "<BR>"
58:
59:       -->
60:       </SCRIPT>
61:
62: </BODY>
63: </HTML> 


Figure 15.6. Results of Listing 15.9.


How the Variable Scope Application Works

A and B are global variables of the VBScript application. The values 5 and 10 are assigned to them, respectively, at the beginning of application execution. Afterwards, program flow is transferred to the subroutine SubroutineA. SubroutineA declares variables A and B as local variables. Due to local variable precedence, whenever A or B is referenced inside SubroutineA, the reference is made to the local variables A and B declared inside SubroutineA. Therefore, lines 24 and 26 of Listing 15.9 print the values 20 and 30 because these values are assigned to the local variables A and B at lines 21 and 22. The situation is almost the same in the case of SubroutineB, which declares its own variable A. Therefore, when a reference is made to variable A within SubroutineB, that reference is made to the local variable declared in SubroutineB. However, because B is not declared as a local variable, all references made to B refer to the global variable B. Finally, lines 54 and 56 print the values of the global variables A and B.

Listing 15.10. Output of the VBScript application in Listing 15.9.

Value of variable A in subroutine A = 20
Value of variable B in subroutine A = 30
Value of variable A in subroutine B = 35
Value of variable B in subroutine B = 10
Value of variable A outside subroutine A and B = 5
Value of variable B outside subroutine A and B = 10

Summary

Data structures store data for future reference and processing. Although VBScript treats all variables as Variant variables, the Variant data type is made up of data subtypes. Depending on the context in which a variable is used, the variable's data assumes a subtype of Variant.


Previous chapterNext chapterContents


© Copyright, Macmillan Computer Publishing. All rights reserved.