MacDevCenter    
 Published on MacDevCenter (http://www.macdevcenter.com/)
 http://www.macdevcenter.com/pub/a/mac/2003/10/17/realbasic.html
 See this if you're having trouble printing code examples


Programming REALbasic, Part 1: Syntax of the Language

by Wei-Meng Lee
10/17/2003

Are you a programmer new to the Mac platform? Or maybe you are one of the millions of VB programmers (like me) who are well versed in the Windows platform and are looking at opportunities in the Mac world. And perhaps you don't have time to learn a new language such as Objective C, C++, or Java. If you fit any of these descriptions (and are trying to leverage your existing skills for Mac development), then with this article, I am going to show you how you can get started in Mac development using REALbasic.

If you are really impatient, I have an article on how to use the IDE included in the REALbasic package: "Building Mac Applications Using REALbasic 4.5 for Mac OS X." In this first article of a series, we shall learn the basic syntax of the language. I am going to assume that you have some programming experience and that you understand basic terms like variables, conditions, assignments, etc. (I won't be touching too much on Mac development in this article, but there is sufficient syntax for you to follow the examples in subsequent articles.)

Reserved Words

One of the first things to learn when programming in a new language is the list of reserved words used by the language. REALbasic has 81 reserved words. Here they are:

And Dim Function Me Raise To
Array Do GoTo Mod Redim TRUE
As Double Handles Module Rem Try
Boolean DownTo If Namespace Return Until
ByRef Each Implements New Select Wend
ByVal Else In Next Self While
Call ElseIf Inherits Nil Shared #bad
Case End Inline68k Not Single #else
Catch Event Integer Object Static #endif
Class Exception Interface Of Step #if
Color Exit Is Or String #pragma
Const FALSE IsA Private Sub
DebugPrint Finally Lib Protected Super
Declare For Loop Public Then

One bit of good news: REALbasic is not case sensitive. So Dim, dim, and diM all refer to the same thing.

Declaring Constants and Variables

Related Reading

REALBasic: TDG

REALBasic: TDG
By Matt Neuburg

Table of Contents
Index
Sample Chapters

Read Online--Safari Search this book on Safari:
 

Code Fragments only

You define constants in REALbasic using the const keyword:

const PI=3.14

To declare variables, use the Dim keyword:

Dim radius as single

You can also declare multiple variables in a single statement.

Dim radius, area as single

In the above example, both radius and area are single variables.

Variables' Scope

Generally, you can declare variables anywhere in your program. However, block scope variables are not allowed, as in the following example:


Dim i as Integer
For i = 1 to 10
  Dim j as integer  ' not allowed
  'j = i * i
Next

Here, the declaration of j is not allowed within the For loop. To declare j, move it outside of the For loop.

Data Types

REALbasic supports the following intrinsic data types:

These five data types are value-typed. Value-type variables store the value directly, as opposed to storing the reference to a value, as in Reference-type variables (more on this later). For example, suppose I have the following declaration and assignment:

Dim number1, number2 as integer
number1=5
number2=number1

Then, changing the value of number1 has no effect on the value of number2:

number1=6
msgbox str(number2) ' prints out 5

Besides the five intrinsic data types, REALbasic variables can also be of the types:

Comments

You can use either one or a combination of the following characters as the delimiter for comments: ', //, and REM.

' This is a comment
// This is also a comment
REM  This is yet another comment!

Mathematical Operators

REALbasic supports the following mathematical operators:

+ Addition
- Subtraction
* Multiplication
/ Division
\ Integer Division
Mod Modulo

The following example illustrates their uses:

Dim ans as variant
Ans = 3+4        ' 7
Ans = 3 - 4      ' -1
Ans = 3*4        ' 12
Ans = 3/4        ' 0.75
msgbox (str(VarType(ans))) ' 5; means Single or Double
ans = 4\3        ' 1
msgbox (str(VarType(ans))) ' 2; means Integer
ans = 4 mod 3    ' 1
ans = 8 mod 4  ' 0

Notice that ans is declared as a variant. Its data type changes, depending on what is assigned during runtime. To check the data type of ans during runtime, use the VarType() function.

Arrays

An array is simply a collection of data of the same type. Simply append a pair of parentheses to your variable to declare it as an array. Here are some examples:

Dim num1() as integer   ' dynamic size; use Redim during runtime
Dim num1(-1) as integer ' same as above
Dim num2(0) as integer ' only 1 element
Dim num3(4) as integer ' 5 elements; indices 0 to 4

Note that you cannot assign array values during declaration. The following is not allowed:

Dim num4() as integer = {1,2,3} ' not allowed
num3() = {1,2,3,4,5}            ' also not allowed

Also, arrays cannot be assigned directly, as in:

num1= num2  ' not allowed

You have to assign array values individually:

num3(0)=5
num3(1)=1
num3(2)=3
num3(3)=4
num3(4)=2

You can sort arrays using the Sort() method:

num3.sort

To verify that the array has been sorted, print it out:

Dim index as integer
For index = 0 to 4
  msgbox Str(num3(index))
Next 

Once an array has been declared, you can:

The following example shows some array manipulations:

Dim str5(2) as string    ' array of 3 elements
str5(0) = "z"            ' assign value to each element
str5(1) = "B"
str5(2) = "a"
str5.append "b"          ' add one element to the array; str5(3)= "b"  
str5.insert 2, "g"       ' str(2) becomes "g", the rest is 
                         ' pushed downwards
str5.remove 2            ' remove str(2)
str5.sort                ' sort the array
For index = 0 to UBound(str5)
  msgbox (str5(index))
Next 
ReDim str5(9)            ' redimension str5 to 11 elements

Unlike VB.NET (or VB6), the ReDim statement automatically preserves the values of the previous elements. Of course, if the new array size is less than the original one, then you will lose some of the elements.

You can also create multi-dimensional arrays:

Dim str1(1,1) as string ' creates a 2 by 2 array of string
str1(0,0) = "REALbasic"
str1(0,1) = "is"
str1(1,0) = "easy"
str1(1,1) = "to use."

Functions and Subroutines

REALbasic supports both functions and subroutines. A function returns a value, while a subroutine does not.

Function AlsoDoSomething(i as Integer) as Double
   ' blocks of code
End function

Sub doSomething(ByVal i as Integer, ByRef j as Single)
   ' blocks of code
End sub

Both subroutines and functions can take input parameters. By default, arguments are passed in by value (ByVal). You can also pass in arguments by reference (ByRef).

The following shows how to call the subroutines and functions above:

Dim result as double
result = alsodosomething(5)
alsodosomething(5)               ' not allowed; must use return value 
result = alsodosomething()       ' not allowed; must supply arguments

Dim num as single
doSomething (5, 4)               ' not allowed; second argument must
                                 ' be a variable
doSomething (5, num)

Using Objects

REALbasic is an event-driven programming language that uses the object-oriented programming paradigm. You will use many objects in your REALbasic programming. Some examples of objects are the controls on your window, such as the PushButton control, PopupMenu control, etc. I won't go into the basics of object-oriented programming at this point, but I will assume that you are already familiar with basic OO concepts such as properties, methods, etc.

I will highlight two special keywords in REALbasic that are worth knowing: self and Me.

The self keyword is a reference to an object's parent object. As an example, suppose you want to set the title of your window to Windows 1. The following two statements are equivalent:

Window1.title = "Window 1"
   ' or
self.title = "Window 1"

The Me keyword is a reference to an event handler's control. Suppose you are writing the event handler that is fired when a PushButton control is clicked. The following two statements are equivalent:

Sub Action()
   Pushbutton1.enabled=false
   ' or
   Me.enabled=false
End Sub

Objects are reference-type variables. That is, their values are not stored directly. Instead, they point to another storage location. As an example, consider the following example, where I have declared a Dictionary object (an object that contains a list of key-value pairs):

Dim dict as Dictionary

To instantiate the Dictionary object, I need to use the new keyword:

dict = new Dictionary

Note that you cannot combine the declaration and instantiation, as you commonly do in VB.NET:

Dim dict as new Dictionary   ' Not allowed!

You can use the Dictionary object like so:

dict.value("Name") = "Wei-Meng Lee"
dict.value("ID") = "WML"
dict.value(0) = 2345

When I try to assign the dict object to another (dict2) and make changes to dict2:

dim dict2 as dictionary
dict2=dict
dict2.value("Name") = "Wei-Meng"

The changes in dict2 are reflected in dict:

msgbox dict.value("Name")  ' prints out Wei-Meng

Making Decisions

REALbasic supports the usual decision-making constructs, such the If-Then-Else construct:

Dim dayofWeek as integer
Dim day as string
dayofWeek = 3

if i<1 or i>7 then
  msgbox "Invalid value for i"
end if 
  
if i>=1 and i<=7 then
  msgbox "Valid value for i"
end if
  
if day<>"error" then
  msgbox "No error"
end if

The comparison operators are:

=Equal
<Less than
<=Less then or equal to
>Greater than
>=Greater than or equal to
<>Not equal to

The logical operators supported are AND, OR, and NOT.

The If-Then-Else construct can also be nested, as the following shows:

if dayofWeek=1 then
  day="Monday"
else 
  if dayofWeek=2 then
    day="Tuesday"
  else 
    if dayofWeek=3 then
      day="Wednesday"
    else
      if dayofWeek=4 then
        day="Thursday"
      else
        if dayofWeek=5 then
          day="Friday"
        else
          if dayofWeek=6 then
            day="Saturday"
          else
            if dayofWeek=7 then
              day="Sunday"
            else
              day="Error"
            end if
          end if
        end if
      end if
    end if
  end if
end if

However, you can rewrite the above code with the elseif keyword, which makes it much shorter:

if dayofWeek=1 then
  day="Monday"
elseif dayofWeek=2 then
  day="Tuesday"
elseif dayofWeek=3 then
  day="Wednesday"
elseif dayofWeek=4 then
  day="Thursday"
elseif dayofWeek=5 then
  day="Friday"
elseif dayofWeek=6 then
  day="Saturday"
elseif dayofWeek=7 then
  day="Sunday"
else
  day="Error"
end if

A better way is to use the Select-Case construct:

select case dayofweek
case 1
  day ="Monday"
case 2
  day ="Tuesday"
case 3
  day ="Wednesday"
case 4
  day ="Thursday"
case 5
  day ="Friday"
case 6
  day ="Saturday"
case 7
  day ="Sunday"
else
  day = "error"
end select

Looping Constructs

Finally, REALbasic supports a number of looping constructs. The following examples are self-explanatory:

Dim i as integer
'---For loop
For i = 0 to 9 step 1  ' default is step 1
  ' do something
Next

For i = 9 downTo 1     ' in descending order
  ' do something
Next
  
'---While-Wend
While (i<=9)
  ' do something
Wend
  
'---Do-Loop Until
Do 
  ' do something
Loop Until(i>9)

'---Do-Until Loop
Do Until (i=10)
  ' do something
Loop

Summary

I hope you have a better feel of the REALbasic language after reading this article. With this foundation, you will be ready to dive deep into the world of REALbasic programming! In the next few articles, I will show you how you can develop Mac applications that you have always drooled at!

Wei-Meng Lee (weimenglee.blogspot.com) is a technologist and founder of Developer Learning Solutions, a technology company specializing in hands-on training of the latest Microsoft technologies.


Return to the Mac DevCenter

Copyright © 2007 O'Reilly Media, Inc.