Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

Writing REALbasic Code

  • Print
  • + Share This
This chapter is from the book

Mastering Dim and Assignment Statements

The code that you write in a REALbasic handler or method is like a recipe: It's a sequence of instructions to be carried out in order. Many of these instructions manipulate data, and the assignment statement is the primary way to manipulate data in REALbasic programs. You met the assignment statement in Chapter 3; here, you'll see how to use it with specific types of data and with variables and properties.

Before a variable can be used, it must have a data type assigned to it. You do this with the Dim statement.

To create a variable:

  • Use the Dim statement:

    Dim myVar as string
    Dim lengthMyVar as integer
    Dim i,j,k as integer


  • Any Dim statements in a handler must appear first, before any other statements in the handler (Figure 4.21).

    Figure 4.21Figure 4.21 Any Dim statements in a handler must appear before any other statements.

To create a variable that is an object: BL

  • Use the Dim statement:

    Dim c as clipboard

    Now you can access the properties of this object:

    me.text = c.text

Variables can be created as simple data types such as integer, string, and Boolean, as shown earlier in this section; or as specific object types, such as windows, list boxes, and the Clipboard. They can also be created as containers for more than one value at a time. A variable that contains several values of the same type is called an array.

To create an array:

  • Use the Dim statement, specifying the dimension of the array:

    Dim customer (100) as string

    This statement sets aside space for 100 strings, each of which can be referred to by its index:

    customer(0) = "Charlie Adams"
    customer(99) = "D. Zanuck"

    Arrays are zero-based: Their indexes start at 0 and go to 1 less than the dimension in the Dim statement. So the preceding two strings are the first and last in the customer array.

To create a multidimensional array:

  • Use the Dim statement, and supply two or more dimensions:

    Dim Chessboard (8,8) as string

    This code creates an 8 x 8 array of values whose type is string. You could refer to a cell in this array this way:

    Chessboard(0,0) = WhiteQueensRook

    After you have created a variable, you can use it.

To assign a string value to a variable:

  • Place the variable on the left side of the equals sign (=) and the value it is to get on the right side (Figure 4.22):

    Figure 4.23Figure 4.22 Assigning a string value to a string variable.

    Dim Mother, Father, Child (20) as string
    Mother = "Barb"
    Father = "Earl"
    Child(1) = "Doc"
    Child(2) = "Mark"
    Child(3) = "Ginny" 

    You can also use this form of the assignment statement, which makes clearer what is being assigned to what:

    Let Mother = "Barb"

To assign a string to a property:

  • Whatever appears on one side of the equals sign in an assignment must be the same type as what appears on the other side. So both of these statements work

    window.title = "Dorothy's Dog"
    window.title = someStringVariable

    because the window.title property is of type string.

To assign a property's value to a string variable:

Assuming that someStringVariable has been created as a string variable, someStringVariable = window.title will put the window's title in someStringVariable.


  • You can never put a quoted string on the left side of an assignment statement. It's easy to see why. Unlike variables and properties, a string such as "Hello Dolly" is not a container to put a value in; it is a value. In general, you can't place a value to the left of an assignment statement.

To concatenate strings:

  • Use the plus-sign operator (+) to combine two strings:

    Dim FullName, FirstName, LastName as
    FullName = FirstName + LastName

    You can combine any number of strings in this way. To make the preceding example work, you probably want to put a space between the first and last names (Figure 4.23):

    FullName = FirstName + " " + LastName

    Figure 4.23Figure 4.23 Concatenation: building up long strings from short ones.

To determine the length of a string:

  • One of the methods that REALbasic supplies for working with strings is len. len is a function, which means that it returns a value to you. When you give it a string, len returns an integer that is the number of characters in the string:

    Dim s as string, ls as integer
    s = window1.title
    ls = len(s)


  • Functions return values. Anywhere in your code that a value of a particular data type is appropriate, a call to a function that returns that data type is appropriate. If i is of integer type, you can assign an integer value to it:

    i = 47

    You can also assign the value of a function that returns an integer value to it:

    i = len(s1).

To extract part of a string:

  • REALbasic supplies three methods for extracting part of a string: left, right, and mid. You give left a string and n, the number of characters you want, and the method returns the first n characters of the string. Similarly, right returns the last n characters. mid takes three parameters: the string, the starting position in the string, and the number of characters to grab, counting from that position. So the following will put "The" in L, "Beagle" in R, and "Voyage" in M (Figure 4.24):

    Figure 4.24Figure 4.24 Using string functions to extract part of a string.

    Dim S, L, R, M
    S = "The Voyage of the Beagle"
    L = left(S,3)
    R = right(S,6)
    M = mid(S,5,6)

    Another string method, instr, can be used to get the location of a substring in a string. instr takes the string and the substring as parameters and returns an integer that is the position of the beginning of the first occurrence of the substring in the string. If the substring isn't in the string, instr returns 0.

    instr("The Voyage of the Beagle",

    returns a value of 5, whereas

    instr("The Voyage of the Beagle", "Trip")

    returns a value of 0. To test for the occurrence of a substring in a string and get a Boolean result, compare the result of instr with 0 (Figure 4.25):

    instr(theString,theSubstring) > 0

    Figure 4.25Figure 4.25 Using the instr function to search for one string inside another.


  • Information stored in computers is normally measured in bytes; kilobytes; megabytes; or if there is a lot of it, gigabytes. A single byte of text is equal to one character—sometimes. Sometimes, it isn't. REALbasic supplies string functions for both situations. Normally, you'll use len. But if you know that the string represents binary data rather than characters, use lenb. Other string functions (such as left, mid, and right) also have their binary versions (leftb, midb, and rightb).

To replace part of a string:

  • If s1, s2, and s3 are strings,


    returns s1 with the first occurrence of s2 replaced by s3.

    If s3 is empty, this same code deletes the first instance of s2 in s1.

    If s1 or s2 is empty, the code does nothing.

    To replace all instances of s2 in s1 with s3, use

    replace and replaceAll are case-

    insensitive; they treat uppercase and lowercase letters the same.

To remove spaces from the beginning or end of a string:

Use one of the following:

  • dim s as string
    s = " Holly Golightly "
    s = trim(s)
    leaves "Holly Golightly" in s 

    (Figure 4.26).

    Figure 4.26Figure 4.26 Functions for manipulating strings.

  • dim s as string
    s = " Holly Golightly "
    s = ltrim(s)
    leaves "Holly Golightly " in s.
  • dim s as string
    s = " Holly Golightly "
    s = rtrim(s)
    leaves " Holly Golightly" in s.

To change the case of string data:

  • This string function returns the string given to it, with all uppercase letters converted to lowercase:

  • This one converts all the characters to uppercase:

  • And this one converts all the characters to lowercase and then converts the first letter of each word to uppercase:


The result, for example, is This Is Titlecase (Figure 4.27).

Figure 4.27Figure 4.27 Functions for controlling the case of string data.

To determine the ASCII value of a string:

  • Use the asc or ascb function:

    i = asc("z")
    newAsc = asc(c1) + 32

To convert a number to a string:

Use one of the following:

  • dim s as string, n as integer

    n = str(s)
  • dim s as string, n as integer

    n = cstr(s)

    The cstr function uses the settings in your International Preferences dialog or Numbers control panel to interpret numbers. Use it if your Mac is not using a period (.) as the delimiter for decimal numbers.

  • dim s, fmtspec as string, n as integer

    s = format(n,fmtspec)

    The format function gives you detailed control of the formatting of a number as a string. The fmtspec parameter specifies the formatting according to a simple code. See the Online Language Reference for details (Figure 4.28).

    Figure 4.28Figure 4.28 Converting a number to a string.

To convert a string to a number:

Use one of the following:

  • dim n as double
    n = val("27")

    puts the value 27 into n.

  • dim n as double
     n = cdbl("27")

    does the same, but uses the settings in your Mac's International Preferences dialog or Numbers control panel to determine how to interpret the number.

    Both functions, val and cdbl return a double as their result. The string passed to these functions is assumed to represent a decimal number unless it is prefixed by &O, &H, or &b, which indicate an octal, hexadecimal, or binary number, respectively. The string that follows this prefix must be appropriate to that number's base. A binary number can contain only 1s and 0s, for example. Both functions ignore any characters after and including the first character that is not a proper character in the indicated base (Figure 4.29).

    Figure 4.29Figure 4.29 Converting a string to a number.

To assign a numeric value to a variable:

Use one of the following:

  • dim n as integer
    i = 365

    An integer is a whole number in the range -2,147,483,648 to 2,147,483,648.

  • dim n as single
    i = 3.14159

    A single is a real number—that is, a decimal number. It takes up 4 bytes of memory.

  • dim n as double
    i = 3.14159

    A double is a real number—that is, a decimal number. It takes up 8 bytes of memory, double the number of bytes used by a single. Doubles give higher precision in calculations than singles do, but calculations with doubles run slower.

To do math with variables:

  • You can combine mathematical values by using any of the basic mathematical operators in any combination (Table 4.1).

    Table 4.1 Mathematical Operators






    A + B



    A - B



    - B



    A * B



    A / B


    Integer division

    A \ B

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020