VBScript Data Types: The Many Faces of the Variant

VBScript Data Types The Many Faces of the Variant

Unlike Visual Basic and Visual Basic for Applications, VBScript has only a single data type, called a variant. A variant is a very special data type, since it can contain many different types of data and can automatically select the most appropriate data type for the particular context in which it is being used. A simplified view of a variant is that it can hold both string data (characters) and numerical data as well as other data, such as dates, Booleans, and objects. Internally it is much more complex, which permits it to hold a wide range of different numeric types.

3.1.1 Variant Data Types

While the only data type recognized by VBScript is the variant, any item of variant data belongs to a particular type. Let's look at the range of types or the different types of data that a variant can hold:

Empty

Empty is a type that consists of a single value, also called Empty, that is automatically assigned to new variables when you declare them, but before you explicitly assign a value to them. For instance, in the code fragment:

Dim var1, var2
var2 = 0

the type of var1 is Empty, whereas var2 is only Empty for the brief period of time between the execution of the Dim statement on the first line (which declares a variable; it is discussed later in this chapter in Section 3.2.5) and the assignment statement on the second line. In addition, a variable's type is Empty if it has been explicitly assigned a value of Empty, as in the following code fragment:

Dim var1
var1 = Empty

Null

Null is a special type that consists of a single value, also called Null, that is used to indicate that a variable does not contain any valid data. Typically, a Null is used to represent missing data. For instance, a variable called JanSales might be assigned a value of Null if the total of January's sales is unknown or unavailable. This must be done by explicit assignment, as in the statement:

JanSales = Null

Because it represents missing data, once a Null value is assigned to a variable, it propagates to any variable whose value results from the value of the original variable. For instance, in the code

Dim JanSales, FebSales, MarSales, Q1Sales
' At this stage, all four variables are Empty

JanSales = 1276000
FebSales = 1000000
MarSales = Null
' We now have made MarSales Null

Q1Sales = JanSales + FebSales + MarSales
' Because MarSales is Null, Q1Sales will also be Null

the value of Q1Sales will be Null, since its value results from an expression that also includes a Null value. Because the Null type represents missing or unknown data, this makes sense: if March's sales data is unknown, then any value that wholly or partially results from it, such as the total sales for the first quarter, must also be unknown.

Boolean

The Boolean type can contain either of two values, True or False. The keywords True and False are constants (if you're not sure what a constant is; see Section 3.2 later in this chapter) that are predefined in VBScript, so you can make use of them in your code when you want to assign a Boolean value to a variable, as the following code fragment shows:

var1 = True
var2 = False

Many object properties have possible values of True or False, such as the Drive object's IsReady property. In addition, Boolean variables within programs often serve as flags to control program flow, as the following code fragment shows:

If Not myBool Then
 myVar = 4
 myBool = True
Else
 myVar = 5
 myBool = False
End If

Note that this example toggles (or reverses) the value of myBool within the If...Else...End If construct.

Byte

A Byte is the smallest numeric type available in VBScript. One byte (8 binary bits) can represent 256 integer numbers, ranging from 0 to 255 in decimal or 00 to FF in hexadecimal. Because the Byte is an unsigned data type, only zero or positive integers are valid Byte values. Attempting to convert a value outside this range to a Byte results in a runtime error.

Integer

An Integer is a whole number that VBscript uses two bytes (or 16 bits) to store in memory. Since one bit is used to represent the sign (either positive or negative), the value of Integer data can range from -32,768 to 32,767. Attempting to convert a value outside this range to an Integer results in a runtime error.

Long

A Long is a signed integer that VBscript stores in four bytes (or 32 bits) of memory. This allows it to hold a far greater range of negative or positive numbers than the Integer type; the value of a Long can range from -2,147,483,648 to 2,147,483,647.

Single

The three numeric data types that we've examined so far (Byte, Integer, and Long) are all integers; they're unable to represent fractional numbers. Fractions can be handled by a floating-point data type, two of which are available in VBScript. The first is Single, which is an abbreviation for single precision; it represents numbers with about seven digits of precision. Because of the large and small numbers involved, we are forced to specify the ranges as exponential numbers. There are two ranges, one for negative values and one for positive values. A negative single precision value can range from -3.402823E38 to -1.401298E-45, while the range of a positive single precision value is 1.401298E-45 to 3.402823E38. A Single can also have a value of zero.

If you need to use a floating-point number in VBScript, there is no reason to use a Single; use a Double instead. Generally, Singles are used because they offer better performance than Doubles, but this is not true in VBScript. Not only are Singles not smaller than Doubles in the VBScript implementation, but the processor also converts Singles to Doubles, performs any numeric operations, and then converts Doubles back to Singles.

Double

The Double type stores a double precision floating-point number; basically, it's the industrial-strength version of the Single data type. Its value can range from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values. A Double can also have a value of zero.

Date/Time

The Date type represents the date or time. If the number holds a date value, the earliest date that can be represented is January 1, 100, and, taking the view that our web sites will be around for a long time, the furthest into the future that we can go is December 31, 9999.

A literal date can be defined by surrounding the date with the # symbol. For example:

Dim myvacationDay
myVacationDay = #01/10/03#

Currency

The Currency type provides a special numeric format for storing monetary values that eliminates floating-point error. Because of this, it, rather than the floating-point types, should be used when working with monetary values. Its value can range from 922,337,203,685,477.5808 to 922,337,203,685,477.5807.

String

The most commonly used VBScript data type isString, which can contain virtually an unlimited number of characters the theoretical limit is the size of the address space, which is two billion bytes on Win32 systems. In practice, though, strings in scripted applications should never be longer than a few thousand bytes at most. The String type used in VBScript is a variable length data type, so you don't have to worry about specifying how much memory to allocate to the variable, as you do in some programming languages.

Object

This data type contains a reference to an object. TheObject type includes the intrinsic VBScript Err object, as well as objects defined by the Class ... End Class construct. It also represents references to external COM objects instantiated with the CreateObject or GetObject methods. If we view script as the "glue" that binds the services provided by components together, then the Object is the most important data type supported by VBScript.

Error

The Error type contains an error number and is typically used to signal a missing argument or other condition resulting from missing data. Typically, Error variants are returned by calls to Visual Basic component methods. VBScript itself does not allow direct creation or manipulation of Error variants.

So what does all this mean to the VBScript programmer? Above all, it means simplicity: as with any well-designed system, the variant is complex, but not complicated. That is to say, the interface the part that you deal with is straightforward, yet behind the scenes the variant data type does some incredibly complex things, which means you don't have to concern yourself with juggling code to ensure that data types are not mismatched, as Example 3-1 shows.

Example 3-1. The power of the variant data type


 

The Variant #1

 

VBScript's Automatic Data Type Conversion

<% Dim vVar1, vVar2, vResult vVar1 = 1 vResult = 1 vVar2 = 50000000.2658 vResult = vVar1 + vVar2 %> The result of adding <%=vVar1 %> and <%=vVar2 %> is <%=vResult %>.

When the user requests the ASP page, its script executes. It begins by using the Dim statement to declare three variables. Next, it assigns the integer value 1 to the first variable, vVar1, and to the third variable, vResult. Just to make things interesting, it assigns a large, double-precision number, 50,000,000.2658, to the second variable, vVar2. Then the routine adds the two variables together and stores their result to the integer variable vResult. As you may recall from the overview of data types, the value assigned to an integer cannot exceed 32,767, nor can it include any digits to the left of the decimal. Yet our script does not generate a compiler error because of this. So in the process of performing the calculation, the VBScript engine converts vVar1 to a double-precision number. In most other programming languages, this task would have to be performed by the programmer.

If you modify the VBScript code in Example 3-1 to try different values for Var1 and Var2, you'll find that the only time that the variant cannot handle the conversion occurs when one of the expressions is a String i.e., you can't add 100 to "Hello" and expect a valid result. When this happens, the VBScript engine displays a "Type mismatch" error, which indicates that one of the items of data was of the wrong type and the engine was unable to convert it. This raises a good point, though: in a numeric operation, it is possibleespecially if the data is input by the user into an HTML form or a dialog produced by the InputBox functionthat one or more of the variables is a string data type. How would you be able to know this in advance, before VBScript stops executing your script and displays an error message?

3.1.2 Determining the Variant Type

Having the variant data type take care of all your data typing is all well and good, but what happens when you need to know exactly what type of data is stored to a variable? VBScript provides two easy-to-use functions, VarType, which returns an integer that indicates the type of data stored to a variable; and TypeName, which returns the name of the data type.

3.1.2.1 VarType

The syntax of VarType is:

VarType(expression)

where expression is an expression whose type you want to determine; you can provide the name of only a single variable at a time. Table 3-1 lists the possible values returned by VarType and the data types that they represent. For purposes of reference, Table 3-1 also lists the VBScript constants that you can use in your code to compare with the values returned by the VarType function; for details, see Section 3.2.3 later in this chapter.

Table 3-1. The values returned by the VarType function

Value

Data type

Constant

0

Empty

vbEmpty

1

Null

vbNull

2

Integer

vbInteger

3

Long

vbLong

4

Single

vbSingle

5

Double

vbDouble

6

Currency

vbCurrency

7

Date

vbDate

8

String

vbString

9

Object

vbObject

10

Error

vbError

11

Boolean

vbBoolean

12

Array of Variant

vbVariant

17

Byte

vbByte

8192

Array

vbArray

Before we see how you use VarType within a script, we should quickly note the value returned by VarType if it detects an array. Actually, the function never returns 8192 or vbArray, as shown in Table 3-1. 8192 is only a base figure that indicates the presence of an array. When passed an array, VarType returns 8192 plus the value of the array type. For a VBScript array, it returns 8192 (or vbArray) plus 12 (or vbVariant), or 8204. For a string array returned by a COM object, for instance, it returns 8200 (vbArray + vbString).

Example 3-2 provides a simple WSH script that uses the VarType function. It assigns a value of 9 to the MyVal variable and calls the VarType function, passing to it MyVal as a parameter. The value returned by the function, 2, is then displayed in a message box; this indicates that MyVal is an Integer.

Example 3-2. The VarType function

Dim MyVal
MyVal = 9
MsgBox VarType(MyVal)

Try modifying this code by assigning various numbers and strings to MyVal. You'll find that you can enter a very large integer for MyVal and the code will return 3 for Long, or you can enter a word or string (enclosed in quotation marks) and the code will return 8. You can even enter a number in quotation marks and it will return 8, indicating a String.

3.1.2.2 TypeName

The TypeName function returns the actual variant type rather than a number representing the data type. The syntax for TypeName is:

result = TypeName(expression)

Like its older brother, TypeName is read-only, which means that you can use it to determine the type of a variable, but you can't use it to explicitly set the type of a variable; to do this, you must use the conversion functions discussed in the next section. Table 3-2 shows the string that the TypeName function returns for each data type.

Table 3-2. Strings returned by the TypeName function

Return value

Description

Actual type name of an object

Boolean

Boolean value: True or False

Byte

Byte value

Currency

Currency value

Date

Date or time value

Decimal

Decimal (single-precision) value

Double

Double-precision floating-point value

Empty

Uninitialized

Error

Error

Integer

Integer value

Long

Long integer value

Nothing

Object variable that doesn't refer to an object instance

Null

No valid data

Object

Generic object

Single

Single-precision floating-point value

String

Character string value

Variant( )

Variant array

Unknown

Unknown object type

Of interest in Table 3-2 is thevariant array type, which is not listed in the VBScript official documentation. Whenever you pass the name of an array to TypeName, even an array that you have forced to be a certain data type by using the conversion functions, the return value is always "Variant( )". Unfortunately, because VBScript does not support strong typing, there's no clear answer as to what data type lurks within your array; you can determine the data type of only one element at a time.

As for making your code easier to maintain, just look at this snippet:

If TypeName(x) = "Double" Then

Now you've no excuse for getting those nasty "type mismatch" errors!

Example 3-3 illustrates the use of TypeName. When you type something into the text box and press the OK button, a message box indicates whether you entered a string, a date, or a number. You may notice, though, that it always identifies (or perhaps misidentifies) numbers as data of type double. That's because our script uses the CDbl function to arbitrarily convert a numeric string entered into the text box to a variable of type double; for details on converting data from one type to another, see the following section.

Example 3-3. The TypeName function

Dim sInput, vResult
Do

 sInput = InputBox("Enter a data value:" , " TypeNameFunction", " ")
 If sInput = " " Then Exit Do
 
 If IsDate (sInput) Then
 vResult = CDate (sInput)
 ElseIf IsNumeric (sInput) Then
 vResult = CDbl (sInput) 
 Else
 vResult = Trim (sInput)
 End If
 
 MsgBox TypeName(vResult)
Loop While Not sInput = " "

3.1.3 Converting from One Data Type to Another

VBScript provides us with a range of built-in conversion functions that are simple and quick to use. The syntax for each is basically the same. For example:

CBool(expression)

where expression is either the name of a variable, a constant, or an expression (like x - y). The conversion functions supported by VBScript are:

CBool

Converts expression to a Boolean. expression can contain any numeric data type or any string capable of being converted into a number.

CByte

Converts expression to aByte. expression can contain any numeric data or string data capable of conversion into a number that is greater than or equal to 0 and less than or equal to 255. If expression is out of range, VBScript displays an Overflow error message. If expression is a floating-point number, it is rounded to the nearest integer before being converted to byte data.

CDate

Converts expression to a Date/Time. CDate accepts numeric data and string data that appears to be a date, converting it to the correct format for the machine. The date is returned in the format specified by the locale information on the client computer. On a machine set to the American date format mm/dd/yy, if you enter the British date format dd/mm/yy in a text box and then use the CDate function on the contents of the text box, CDate will convert it to the American mm/dd/yy format.

CCur

Converts expression to a Currency. CCur accepts any numeric or string data that can be expressed as a currency value. The function recognizes the decimal and thousands separators based on locale information on the client computer.

CDbl

Converts expression to a Double. The function accepts any numeric data within the limits of the Double or any string data that can be converted to a number within the range of the double data type.

CInt

Converts expression to an Integer. CInt accepts any numeric data within the limits of the Integer or any string data that can be converted to a number within the limits of the integer data type.

CLng

Converts expression to a Long. The function accepts any numeric data within the limits of the long integer data type or any string data that can be converted to a number whose value lies within the range of a long integer.

CSng

Converts expression to a Single. The function accepts any numeric data within the limits of the Single or any string data that can be converted to a number within the range of the single data type.

CStr

Converts expression to a String. CStr accepts any kind of data.

So now you know what data types VBScript can handle and how to convert from one type to another. You know how to find out how the variant is handling your data, and you can convert from one type to another. Let's now look at how you're going to use these data types and data within your scripts.

Part I: The Basics

Introduction

Program Structure

Data Types and Variables

Error Handling and Debugging

VBScript with Active Server Pages

Programming Outlook Forms

Windows Script Host 5.6

VBScript with Internet Explorer

Windows Script Components

Part II: Reference

Part III: Appendixes

Appendix A. Language Elements by Category

Appendix B. VBScript Constants

Appendix C. Operators

Appendix E. The Script Encoder



Vbscript in a Nutshell
VBScript in a Nutshell, 2nd Edition
ISBN: 0596004885
EAN: 2147483647
Year: 2003
Pages: 335

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net