Chapter 5: Visual Basic and REALbasic

In This Chapter

bullet Understanding the structure of a BASIC program

bullet Declaring variables

bullet Using mathematical operators

bullet Branching and looping statements

bullet Creating data structures and objects

Since its origins as a teaching language, the BASIC language has evolved dramatically, incorporating structured programming techniques (which was once the strength of languages like Pascal) and object-oriented features (which were once available only in languages like C++). Writing a program in BASIC is usually faster and easier than writing an equivalent program in another programming language, such as C++.

Despite its ease of understanding, BASIC has three drawbacks: speed, hardware access, and portability. BASIC programs typically run much slower than equivalent C++ programs, so if speed is critical, such as creating a real-time program that monitors airplane controls or a patient’s heart condition, BASIC may not be the best choice.

BASIC deliberately limits access to the computer’s hardware, such as memory, which makes BASIC unsuitable for writing hardware-dependent programs such as disk defragmenters, operating systems, or anti-virus programs.

Because BASIC language has evolved over the years, numerous dialects of BASIC have emerged, so programs written in one type of BASIC dialect often won’t run on another computer that uses a different BASIC dialect. This problem is most prominent when programmers use Visual Basic (www.microsoft.com/express/vb), which runs only on Windows computers.

To avoid this problem, another popular version of BASIC, dubbed REALbasic (www.realbasic.com), offers cross-platform capabilities so you can write a single REALbasic program that runs on Windows, Linux, and Mac OS X with little or no modification. The REALbasic language is similar to Visual Basic, which makes it possible to translate or port a Visual Basic program into REALbasic so you can create a Linux or Macintosh version of a Visual Basic program.

Both Visual Basic and REALbasic are the most prominent BASIC dialects that offer structured programming and object-oriented programming. Two simpler BASIC dialects that omit object-oriented features are Liberty BASIC (www.libertybasic.com) for Windows and Chipmunk BASIC (www.nicholson.com/rhn/basic) for the Macintosh. You can also visit the Run BASIC site (www.runbasic.com) to practice writing BASIC programs through any browser.

The Structure of a BASIC Program

In the original BASIC language, a program consisted of one or more commands listed one after another, such as

PRINT “This is a simple BASIC program”

END

For creating simple programs, BASIC lets you get started right away by focusing only on the commands you need. To create more complicated programs, you can create a single main program and one or more subprograms. The main program always runs first and determines when to run commands stored in different subprograms.

In both Visual Basic (VB) and REALbasic (RB), there’s no main program. Instead, a typical VB/RB program consists of a single project file that lists the names of all files that make up that program. The three main types of files used in a project are

bullet Window files

bullet Module files

bullet Class files

Using windows files

A window file contains a single window and various controls that appear on that window, such as buttons, pull-down menus, or sliders. Besides containing the user interface, a window file also contains subprograms that tell each control, on that user interface, how to respond to an event.

Such subprograms, or event subprograms, tell the computer how to respond when the user does something, such as click the mouse or move the mouse over a control. Unlike a traditional BASIC program where the main program determines when and how many times a subprogram runs, a VB/RB program consists of multiple subprograms that may run in the order determined solely by what the user does.

A Visual Basic or REALbasic program typically consists of at least one window file where you place controls, such as buttons, check boxes, or sliders, as shown in Figure 5-1.

Figure 5-1: Creating a Visual Basic or REALbasic program involves placing controls on a window.

Figure 5-1: Creating a Visual Basic or REALbasic program involves placing controls on a window.

Stored inside each window file are event subprograms that tell the computer how to respond when the user clicks or manipulates that control. To create an event subprogram, double-click a control. This creates a blank event subprogram that you can fill with commands that tell the computer what to do.

Using module files

A module file is optional but is often used to store commonly used subprograms. By storing subprograms in separate module files, you can create a library of subprograms that you can copy and plug in to another Visual Basic/REALbasic project. Typically, a VB/RB project consists of zero or more module files.

Using class files

A class file contains BASIC code to define one or more classes, which is used in object-oriented programming to create objects. A typical Visual Basic/REALbasic project consists of zero or more class files. Each time you create a new object, create a new class file. As a result, if you use object-oriented features, your project can consist of dozens of separate class files.

Creating Comments

Visual Basic lets you create comment lines with the apostrophe () or REM keyword, such as

 ‘ The apostrophe defines a line comment

PRINT “This is a simple BASIC program”

REM The REM (Remark) keyword is another way

REM to create a comment

END ‘ This is the end of the program

REALbasic uses both the apostrophe and the REM keyword along with the double slash characters (//), such as

PRINT “This is a simple BASIC program”

END // This is the end of the program

Declaring Variables

In early versions of BASIC, you could create a variable any time you needed it. However as BASIC adopted structured programming techniques, more modern dialects of BASIC (such as Visual Basic and REALbasic) now force programmers to declare variables by defining the variable name and data type. A typical variable declaration looks like this:

Dim VariableName As DataType

VariableName can be any descriptive name, such as SalesTax, Players_on_Team, or MoneyEmbezzled. The data type defines the type of data the variable can hold and the amount of data the variable can hold. You can also declare multiple variables on a single line, such as

Dim VariableName1, VariableName2, VariableName3 As DataType

Declaring string data types

Strings represent text, such as a single character (“A”) or several words (“This is a string of text”). To declare a string variable, use the String keyword, such as

Dim FirstName As String

In Visual Basic (but not in REALbasic), you can also declare a variable as a Char data type, which can only hold a single character, such as the letter “H.” To declare a Char data type, use the Char keyword, such as

Dim Grade As Char

Declaring integer data types

Whole numbers represent integers, such as 39, –1092, or 4. A whole number can be positive or negative. The most common type of integer data type is Integer and is used as follows:

Dim TaxRefund As Integer

Because the range of integers is infinite, you can declare a variable to accept a range of integer values. For example, if a variable only needs to hold a positive value, you can declare it as a Byte data type in Visual Basic, such as

Dim Age As Byte

In Visual Basic, a Byte data type can hold a value from 0 to 255 whereas an Integer data type can hold a value as small as –2,147,483,648 or as large as 2,147,483,647.

Besides limiting the range of integer values, different integer data types also require different amounts of memory to store that data. The greater the range of values you need to store, the more memory needed (measured in bytes). The smaller the range of values, the less memory required. Table 5-1 and Table 5-2 show different integer data types, the memory needed, and the range of values they can hold for Visual Basic and REALbasic.

Table 5-1 Visual Basic Integer Data Types
Data Type Number of Bytes Range
Byte 1 0 to 255
Short 2 –32,768 to 32,767
Integer 4 –2,147,483,648 to 2,147,483,647
Long 8 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Table 5-2 REALbasic Integer Data Types
Data Type Number of Bytes Range
Int8 or Byte 1 –128 to 127
Int16 2 –32,768 to 32,767
Int32 or Integer 4 –2,147,483,648 to 2,147,483,647
Int64 8 –2^63 to 2^63–1
UInt8 1 0 to 255
Uint16 2 0 to 65535
Uint32 4 0 to 4,294,967,295
Uint64 8 0 to 2^64–1

Declaring decimal data types

Decimal values represent numbers such as 1.28 or –90.4. Just as you can limit the range of integer values a variable can hold, so can you limit the range of decimal values a variable can hold. In Visual Basic, the three types of decimal data types are Single, Double, and Decimal (as shown in Table 5-3). In REALbasic, the only two decimal data types are Single and Double (as shown in Table 5-4).

Table 5-3 Visual Basic Decimal Data Types
Data Type Number of Bytes Range
Single 4 –3.402823 E38 to –1.401298 E-45
(negative values)
1.401298 E–45 to 3.402823 E38
(positive values)
Double 8 –1.79769313486231 E308 to
–4.94065645841247 E–324
(negative values)
4.94065645841247 E–324 to
1.79769313486232 E308
(positive values)
Decimal 12 +/–79,228,162,514,264,337,593,
543,950,335 (no decimal point)
+/–7.9228162514264337593543950335
(up to 28 decimal places)
Table 5-4 REALbasic Decimal Data Types
Data Type Number of Bytes Range
Single 4 1.175494 E–38 and 3.402823 E+38
Double 8 2.2250738585072013 E–308 and
1.7976931348623157 E+308

To declare a variable as a Decimal data type, use the Single, Double, or Decimal keyword, such as

Dim TaxRefund As Single

Declaring Boolean values

Besides storing text and numbers, variables can also hold a True or False value, known as Boolean values. To declare a variable to hold a Boolean value, use the Boolean keyword as follows:

Dim House_Is_Empty As Boolean

Declaring generic values

The main reason to declare a variable as a certain data type is to restrict the type of information the data can hold. For example, you don’t want someone to store a negative number in a variable meant to store someone’s age. However, you may need to create a variable that you want to store different types of values, such as strings, numbers, or Boolean values.

In Visual Basic, an Object data type can hold anything, such as

Dim Chameleon As Object

Chameleon = “This is a string”

Chameleon = 89.303

In REALbasic, a Variant data type can hold anything, such as

Dim Chameleon As Variant

Chameleon = “This is a string”

Chameleon = 89.303

Use Object or Variant data types sparingly. If you know a variable should contain only a certain range of data, declare it as a specific data type, such as Integer or Single. This not only reduces the amount of memory to store data, but also speeds up the program and reduces the chance that variables may store incorrect data.

Declaring Constants

Constants always represent a fixed value. In Visual Basic, you can declare a constant, its data type, and its actual value as follows:

Const ConstantName As DataType = Value

So if you wanted to assign 3.14 to a pi constant, you could do this:

Const Pi As Single = 3.14

In REALbasic, you can declare a constant without the data type declaration, such as

Const Pi = 3.14

Using Operators

The three types of operators used are mathematical, relational, and logical. Mathematical operators calculate numeric results such as adding, multiplying, or dividing numbers. Table 5-5 lists the mathematical operators used in Visual Basic and REALbasic.

Table 5-5 Mathematical Operators
Mathematical Operator Purpose Example
+ Addition 5 + 3.4
- Subtraction 203.9 - 9.12
* Multiplication 39 * 146.7
/ Division 45/ 8.41
\ Integer division 35 \ 9 = 3
Mod Modula division (returns the remainder) 35 mod 9 = 8
^ Exponentiation 2 ^ 4

Relational operators compare two values and return a True or False value. The six relational operators available in Visual Basic and REALbasic are shown in Table 5-6.

Table 5-6 Relational Operators
Relational Operator Purpose
= Equal
<> Not equal
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

Logical operators compare two Boolean values (True or False) and return a single True or False value. Both Visual Basic and REALbasic use the same logical operators but Visual Basic includes two additional operators — AndAlso and OrElse, as shown in Table 5-7.

Table 5-7 Logical Operators
Logical Operator Truth Table
And True And True = True
True And False = False
False And True = False
False And False = False
Or True Or True = True
True Or False = True
False Or True = True
False Or False = False
Xor True Xor True = False
True Xor False = True
False Xor True = True
False Xor False = False
Not Not True = False
Not False = True
AndAlso
(only in Visual Basic) True AndAlso True = True
True AndAlso False = False
False AndAlso (never evaluated) = False
False AndAlso (never evaluated) = False
OrElse
(only in Visual Basic) True OrElse (never evaluated) = True
True OrElse (never evaluated) = True
False OrElse True = True
False OrElse False = False

In Visual Basic, the AndAlso and OrElse operators act as faster versions of the traditional And and Or operators. The And operator must always compare two Boolean values, but if the AndAlso operator determines that the first Boolean value is False, it doesn’t waste time evaluating the second Boolean value because one False Boolean value automatically makes the entire AndAlso operator evaluate to False.

The OrElse operator works the same way. If the OrElse operator identifies the first Boolean value as True, it doesn’t waste time evaluating the second Boolean value because it will always evaluate to True anyway.

Branching Statements

The simplest branching statement is an IF-THEN statement that only runs one or more commands if a Boolean condition is True, such as

IF condition THEN

  Command

END IF

To make the computer choose between two mutually exclusive sets of commands, you can use an IF-THEN-ELSE statement, such as

IF condition THEN

  Command

ELSE

  Command

END IF

If a Boolean condition is True, the IF-THEN-ELSE statement runs the first group of commands, but if the Boolean condition is False, the IF-THEN-ELSE statement runs the second group of commands. An IF-THEN-ELSE statement will always run one set of commands or the other.

A variation of this is the IF-THEN-ELSEIF statement, which uses two or more Boolean conditions to choose which of two or more groups of commands to run, such as

IF condition1 THEN

  Command

ELSEIF condition2 THEN

  Command

END IF

Whereas the IF-THEN-ELSE statement can only give the computer a choice of two groups of commands to run, the IF-THEN-ELSEIF statement can offer the computer two or more groups of commands to run, such as

IF condition1 THEN

  Command

ELSEIF condition2 THEN

  Command

ELSEIF condition3 THEN

  Command

END IF

As an alternative to the IF-THEN-ELSEIF statement, you can also use the SELECT-CASE statement, such as

SELECT CASE variable

CASE value1

  Command

CASE value2

  Command

CASE value3

  Command

END SELECT

The preceding SELECT-CASE is equivalent to the following IF-THEN-ELSEIF statement:

IF variable = value1 THEN

  Command

ELSEIF variable = value2 THEN

  Command

ELSEIF variable = value3 THEN

  Command

END IF

To check if a variable matches multiple values, you can separate multiple values with commas or use the TO keyword to match a range of values, such as

SELECT CASE variable

CASE value1, value2, value3

  Command

CASE value4 TO value10

  Command

END SELECT

The preceding SELECT-CASE is equivalent to the following IF-THEN-ELSEIF statement:

IF variable = value1 OR variable = value2 OR variable = value3 THEN

  Command

ELSEIF variable >= value4 AND variable <= value10 THEN

  Command

END IF

Besides checking for exact values, the SELECT CASE statement can also compare values with the <, <=, >, or >= comparison operators, such as

SELECT CASE variable

CASE IS >= value1

  Command

CASE IS < value2

  Command

END SELECT

When the SELECT-CASE statement uses comparison operators, it uses the IS keyword.

The preceding SELECT-CASE statement is equivalent to

IF variable >= value1 THEN

  Command

ELSEIF variable < value2 THEN

  Command

END IF

Looping Statements

A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True. To create a loop that repeats for a fixed number of times, use the FOR-NEXT loop, which looks like this:

FOR variable = Start TO End

  Command

NEXT

If you wanted the FOR-NEXT loop to run five times, you’d set the Start value to 1 and the End value to 5, such as

FOR variable = 1 TO 5

  Command

NEXT

Normally the FOR-NEXT loop counts by one, but you can use the STEP keyword to make the FOR-NEXT loop count by any value, such as by three, as shown in this example:

FOR variable = 1 TO 36 STEP 3

  Command

NEXT

Rather than count up, the FOR-NEXT loop can also count down. In Visual Basic, you can count down by using a negative number after the STEP keywords, such as

FOR variable = 100 TO 1 STEP -1

  Command

NEXT

In REALbasic, you can count down by replacing the TO keyword with the DOWNTO keyword, such as

FOR variable = 100 DOWNTO 1

  Command

NEXT

If you don’t know how many times you need to repeat commands, use a DO loop. The two variations of a DO loop are DO-UNTIL and DO-WHILE (available only in Visual Basic).

The DO-UNTIL loop repeats until a certain condition becomes True. The DO-WHILE loop repeats while a certain condition remains True. The two variations of the DO-UNTIL loop look like this:

DO UNTIL condition

  Command

Loop

In this version, the DO-UNTIL loop checks if a condition is True. If so, this loop never runs. If not, this loop runs at least once. The second variation of the DO-UNTIL loop looks like this:

DO

  Command

Loop UNTIL condition

This loop runs at least once before checking a condition. If the condition is True, the loop stops. The DO-WHILE loops work nearly identically. If you want to make a loop that may run zero or more times, you’d use this DO-WHILE loop:

DO WHILE condition

  Command

Loop

If you want a DO-WHILE loop that runs at least once, you’d use this variation:

DO

  Command

Loop WHILE condition

Although REALbasic lacks the DO-WHILE loop, it does offer a WHILE-WEND loop, which looks like this:

WHILE condition

  Command

WEND

Creating Subprograms and Functions

You can create a subprogram (or a procedure) by using the SUB keyword as follows:

SUB Name (Parameter list)

  Command

END SUB

Every subprogram must have a unique name, which usually describes the purpose of that subprogram, such as Calculate_Velocity or CheckPassword. The parameter list declares variables to hold any data the subprogram may need from another part of the program. For example, a simple parameter list might look like this:

SUB Name (BYVAL Age AS Integer)

  Command

END SUB

The BYVAL keyword stands for By Value and means that the subprogram receives a copy of data sent to it from another part of the program. If the subprogram changes the value of that data, the new value of that data only appears in the subprogram and not in any other part of the program. The BYVAL keyword is optional in REALbasic.

Instead of the BYVAL keyword, you could also use the BYREF keyword, which stands for By Reference, such as

SUB Name (BYREF Age AS Integer)

  Command

END SUB

When accepting data By Reference, a subprogram can change the value of that data, which can affect the rest of the program.

A function is a special version of a subprogram that always returns a single value. To create a function, use the FUNCTION keyword, such as

FUNCTION Name (Parameter list) AS Datatype

  Command

  RETURN value

END SUB

The two main differences between a function and a subprogram (procedure) are that a function needs to include the RETURN keyword and needs to be defined as a specific data type.

The RETURN keyword defines a variable that contains a specific value that the function calculates. This value gets returned back to another part of the program. Because a function represents a single value, you must define the data type of this value, such as an Integer or a String.

Data Structures

Visual Basic provides three data structures:

bullet Structures – Allows storing multiple variables inside a single variable.

bullet Arrays – Stores a list of items of the same data type such as all integers.

bullet Collections – Stores a list of items of different data types.

REALbasic offers two data structures:

bullet Arrays – Stores a list of items of the same data type such as all integers.

bullet Dictionaries – Stores a list of items along with a corresponding key value used to retrieve the data.

Creating a structure

A structure is a variable that typically holds two or more variables. To create a structure (in Visual Basic only), use the STRUCTURE keyword as follows:

STRUCTURE Name

  PUBLIC VariableName AS DataType

END STRUCTURE

The name of a structure can be any descriptive name, such as MyTeam or Accounting_Department. Inside a structure, you must declare one or more variables with the PUBLIC keyword. A typical structure might look like this:

STRUCTURE MyGirlfriends

  PUBLIC Name AS String

  PUBLIC Age AS Integer

  PUBLIC Phone AS String

END STRUCTURE

Creating an array

Arrays in Visual Basic and REALbasic are known as zero-based arrays, which mean that the first element of the array is located at index number 0, the second element of the array is located at index number 1, and so on.

To create an array, declare it with the DIM keyword, specify the number of elements, and define the type of data the array can hold, such as

DIM ArrayName (ArraySize) AS DataType

The array name can be any descriptive name. The array size defines how many items the array can hold. Because the array is zero-based, an array defined as a size 10 can actually hold 11 items. The data type defines the type of data the array can hold, such as all strings or all integers. To create an array that can hold 11 strings, you could define an array like this:

DIM PetNames (10) AS String

If you want an array to grow or shrink while your program runs, you can define a dynamic array. To define a dynamic array, omit the array size and then define the array size right before you start storing items into that array, such as

DIM ArrayName () AS DataType

REDIM ArrayName (ArraySize)

The REDIM keyword tells the program to resize the array.

Creating a collection and a dictionary

Arrays can be too restrictive because they can only hold one data type. For a more flexible alternative, use a collection instead. Two big advantages of a collection over an array are that a collection can hold different data types and can grow and shrink without having to define its size. To define a collection, define a collection name as follows:

DIM Name AS NEW COLLECTION

Unlike arrays where the first item is assigned an index number of 0, a collection assigns the first item an index number of 1.

A variation of a collection is a dictionary (available only in REALbasic). The two main advantages of a dictionary are that you can assign descriptive values, or keys, to each item stored in a dictionary. This makes it easier and faster to retrieve data.

To retrieve an item from a dictionary, specify the key. To retrieve an item from an array or a collection, you must either know the exact position of the item you want or you must search the entire array or collection to find the data you want. As a result, searching for items in a dictionary is much faster and easier than searching for items in arrays or collections.

Creating Objects

To create an object, you must create a separate class stored in a class file. A typical class in Visual Basic looks like this:

PUBLIC CLASS ClassName

  DIM PropertyVariable AS DataType

  PROPERTY PropertyName() AS DataType

    GET

      RETURN PropertyVariable

    END GET

    SET (BYVAL Value AS DataType)

      PropertyVariable = Value

    END SET

    SUB MethodName()

      Commands

    END SUB

END CLASS

In REALbasic, you don’t even have to type any code. Instead, type the name of your class, properties, and methods and then REALbasic takes care of creating the code to define a class.

After you define a class, you can create an object from that class by declaring a variable as a new class type, such as

DIM ObjectName AS NEW ClassName

Both Visual Basic and REALbasic allow only single inheritance where a new class can inherit features from a single class. In Visual Basic, you can create a new class from an existing class by using the Inherits keyword, such as

PUBLIC CLASS ClassName

  INHERITS AnotherClassName

  ‘ Additional code goes here

END CLASS

In REALbasic, you can use a pop-up menu to define a class that you want to inherit from, so you don’t need to type any code at all.