Wiki copymirror

This is a mirror of the wiki at pascal.chat. Editing, history and sign-in are there.

Howdy World (Hello World on steroids)

English · Português · Suomi

This Wiki article is a tutorial for Lazarus. It explains the first steps to get a working piece of software and explains some best practices along the way. The end result is twofold (hopefully): the reader understands the basic concepts of how to build software with Lazarus and she has an actual piece of working software that can be embedded in other programs: a calculator. A calculator is fairly easy to implement and everyone understands its concepts. So no need to describe a lengthy business case beforehand. The calculator is limited to integer calculations, but can easily be extended.

This tutorial does not describe the Lazarus installation process. It is assumed that Lazarus is installed and ready for use (preferably the latest, stable version which is currently Lazarus 2.0.12 with Free Pascal v3.2.0). This tutorial is more or less platform independent (but targeted at thick clients). All screenshots were made on a Windows XP PC; hence the blue/red/grayish color scheme.

Recommended reading before starting here: a comprehensive introduction to the Lazarus IDE.

Let’s get started

It’s best to create a separate directory for every new project. So before getting our feet wet, let’s create a directory to save our Calculator project in (do this with your OS application of choice). This directory will be the root for all files created for the project.

(Text that describes actions that must be executed is bulleted like the previous line.)

With this out of the way it’s time to start a new Lazarus project.

To make sure that all files of our new project end up in the right directory the project must be saved first.

In theory the program that is thus created is a piece of valid software that can be executed. Before compiling it for the first time, two changes are recommended: assigning new locations (directories) for the compiled units and target filename.

The image below is how this would look like on a Windows machine.

By doing this the project folder will not be cluttered with output that is generated by the compiler. The files in the project folder are required to (re-) build the program. Everything in the ’’lib’’ and ’’bin’’ directories can be deleted when archiving the project.

Now as a first test the project can be compiled and run.

If all went well a blank window is displayed. Now we know that a solid basis is created on which we can start building the program.

The first component

Lazarus has a so called ‘component palette’:

All components that are available to build a user interface are logically grouped on the component tabs. The actual number of tabs depends on the installed packages. But the basic palette looks something like the above image. The first tab is Standard, followed by Additional, Common Controls etc.

To retrieve the type name of a component, hover with the mouse pointer above the component icon and a hint is displayed that gives the type name (to be more precise: the class type of the component is displayed). For an explanation of all controls look at this [[Lazarus_Tutorial|Lazarus introduction].

The first thing that needs to be done for the Calculator program is to create a display area where the entered numbers are, well, displayed. For this a TEdit control is used.

Note: the visual components are referred to as Controls. For now the difference between a 'component' and a 'control' is not that relevant.

To place a control on the form, the form must have the focus. Pressing F12 on the keyboard changes the focus from the form editor to the source code editor and vice versa.

Now that the control is placed on the form it can be customized to our needs. This customization takes place in the Object Inspector. That is the window at the left side of the screen with the list of properties for the TEdit control that are customizable.

Properties determine the look and feel and behavior of a control. It’s easy to change a property: just click on one of them, enter a new value and press Enter. The effects on the control are instantly visible. The properties in the Object Inspector are all the properties for one control. In particular the control that has the focus/is selected. The control that is selected can be recognized by the small black squares that surround the control. So the way to change properties of a control is by first selecting it and then make the changes in the Object Inspector. If no control is selected, the form properties are displayed.

Make the following changes to the properties of Edit1.

These properties are pretty self-explanatory. Especially when the above changes are made and the effect is monitored on the form.

As a finishing touch the Font that is used to display texts on all controls will be changed. The font can be changed in two places: the font property of edDisplay or the form’s font property. Changing the font for the form itself has the benefit that all newly placed controls on the form will 'inherit' the new font. So that is where we are going to make the change.

The Form’s title is not very meaningful. The default text 'Form1' is displayed.

The result of all these actions is a form that looks something like this:

Now is a good time to save the form.

Remember to save and save often!

Buttons

What use is a calculator if numbers cannot be entered? So the next step is adding buttons for the digits 0..9. Before placing the buttons for the digits, a so called container is placed on the form. A container defines an area on a form where controls can be grouped together. The form is a container. A TPanel is another container that can be placed on a form. Containers can be placed inside other containers, but that’s for another tutorial.

A new panel is now visible on the form with a default width, height and caption. Note that the font for the panel caption is inherited from the form. This panel will be used to group all buttons, so a number of properties must be changed.

(Increasing the size of the form gives us some space to move controls around.)

Now the digit buttons will be added.

This must be repeated for the digits 1..9. The quickest way to do this is by copy/pasting the 0-button.

Next are the four buttons for the mathematical functions (add, subtract etc.).

And the 'special' buttons:

Not what all buttons are placed, resize the form to fit the buttons tightly.

It should look something like this:

Remember to save and save often!

Responding to events

A Graphical User Interface (GUI) application is often an event-based application. This means that the application does nothing until we tell it to do something. For example by entering data via the keyboard, pressing buttons etc. One of the things the calculator needs to do is respond to mouse clicks on the buttons 0..9. This is where the Lazarus IDE helps us. Adding a so called event handler for a button is easy.

edDisplay.Text := edDisplay.Text + '0' edDisplay is an edit box. The way to change the contents of the edit box is by modifying the Text property. The above statement adds the number '0' to the text in the edit box and this is visible on screen immediately.

edDisplay.Text := edDisplay.Text + '1'

It's a good idea to compile the code from time to time to check for syntax errors (Compile time error).

Of course it's now easy to add event handlers for the digits 2..9, but this will result in a lot of redundant code. Every event handler does exactly the same, only the digit is different. The way to remove this redundancy is by creating a procedure that does the processing, and add the variable data (the digits 0..9) as a parameter.

pascal
  
  { TForm1 }

  TForm1 = class(TForm)
    btnDigit0: TButton;
    btnDigit1: TButton;
    btnDigit2: TButton;
    btnDigit3: TButton;
    btnDigit4: TButton;
    btnDigit5: TButton;
    btnDigit6: TButton;
    btnDigit7: TButton;
    btnDigit8: TButton;
    btnDigit9: TButton;
    btnFunction: TButton;
    btnFunction1: TButton;
    btnFunction2: TButton;
    btnFunction3: TButton;
    btnCalculate: TButton;
    btnPlusMinus: TButton;
    btnClear: TButton;
    edDisplay: TEdit;
    Panel1: TPanel;
    procedure btnDigit0Click(Sender: TObject);
    procedure btnDigit1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

Note that in the above class definition all controls and procedures are declared that we added to the form via 'pointing-and-clicking'. Do not make any manual changes in there!! The IDE will get nervous when you do. The place to add custom variables, procedures and functions is in the private or public sections. As a general rule all custom variables are added to the the private section. Procedures and functions are added to the private section as well, except when other forms need to call these procedures or functions (which shouldn't happen too often).

Back to our digits problem: we need a procedure that adds digits to the display, where the digits themselves can vary.

pascal
  private
    { private declarations }
    procedure AddDigit(const pDigit: byte);
  public
    { public declarations }
  end;

Next the actual code of the AddDigit procedure must be entered. Again the IDE comes to the rescue:

The IDE generates the definition of this new method and places the text cursor inside the empty body. We can immediately start typing.

edDisplay.Text := edDisplay.Text + IntToStr(pDigit) Note that function IntToStr() translates a numerical value, the digit, to a string value so it can be added to the display text.

Now to use this procedure for all digits 0..9:

pascal
procedure TForm1.btnDigit0Click(Sender: TObject);
begin
  AddDigit(0)
end;
pascal
procedure TForm1.btnDigit1Click(Sender: TObject);
begin
  AddDigit(1)
end;

Before completing this sequence for all other digit buttons, make sure that this actually does what we want.

A good programmer is a lazy programmer

Now we can add event handlers to digit buttons 2..9. But then again we have the same problem of creating a lot of redundant code: AddDigit(2), AddDigit(3) etc. What if there were a way to tell the buttons apart? Luckily there is.

All components have an integer property called Tag (remember: a control is just a special kind of component that inherits this Tag property). It is a property that has no actual function. It is there for us to use as we see fit. Now what if each button would have its digit value stored in the Tag property…

Now all digit buttons have a unique Tag value. We didn't change digit button 0 because the default Tag value already is 0.

Now to make use if this Tag value:

procedure TForm1.btnDigit0Click(Sender: TObject); The Sender parameter is actually a reference to the button that was pressed. Via typecasting we can use the parameter as if it was a TButton.

pascal
procedure TForm1.btnDigit0Click(Sender: TObject);
begin
  AddDigit(TButton(Sender).Tag)
end;

It doesn't look like we have accomplished much, replacing one line of code with another. However if we were to add the code for the other digits (1..9) it would look exactly the same. So all other digits can reuse this particular method!

Let's have a closer look at the [IDE Window: Object Inspector|Object Inspector]].

In the object inspector we can not only change the properties of a control but also the event handlers. In the Object Inspector we can see that as soon as digit button 0 is clicked, method btnDigit0Click is called (this is the OnClick event handler).

Now all buttons share one common procedure that does exactly what we want except for digit button 1. Remember that for digit button 1 we created an event handler btnDigit1Click that we don't really need anymore.

Now all buttons share the same event handler to add digits to the display box.

For the digit buttons one final thing needs to be done: event handler btnDigit1Click still exists but is not used anymore and should be deleted. The safest way to do this (for now) is to let the IDE handle it. For this to work the option Auto remove empty methods must be enabled.

From now on all empty methods are automatically deleted as soon as the source file is saved.

Tuning

So far so good: the calculator program compiles, runs and responds to clicks on digit buttons 0..9. But it doesn't behave exactly as we want: there's always this annoying zero at the beginning of the number and the number of allowed digits is too large.

Removing leading zeroes

Normally an integer number that's bigger (or smaller) than zero does not start with a leading zero. So our calculator should compensate for this. Luckily this is easy to implement. Remember that we have one and only one method that handles the addition of digits: AddDigit. This is the place to add logic to suppress the leading zero.

pascal
procedure TForm1.AddDigit(const pDigit: byte);
begin
  // Suppress leading zeroes when adding digits
  if edDisplay.Text = '0' then
    edDisplay.Text := IntToStr(pDigit)
  else
    edDisplay.Text := edDisplay.Text + IntToStr(pDigit)
end;

Limit the number of digits

This demo calculator cannot handle numbers that are too large. So we need to limit the number of digits that can be entered. Again the logical place to do this is the AddDigit method:

pascal
procedure TForm1.AddDigit(const pDigit: byte);
begin
  // Limit the number of digits
  if length(edDisplay.Text) < 8 then
  begin
    // Suppress leading zeroes when adding digits
    if edDisplay.Text = '0' then
      edDisplay.Text := IntToStr(pDigit)
    else
      edDisplay.Text := edDisplay.Text + IntToStr(pDigit)
  end;
end;

Operations

Now it's time to look at the actual operations we want to implement: adding, subtracting, multiplying and dividing. The way the user is going to use the calculator goes something like this:

  1. The user enters a number
  2. The user presses a function button (e.g. '+')
  3. The user enters a second number
  4. The user presses '='
  5. The program responds with the addition of the first and second number

As soon as the user presses the '=' button the program has to know three things:

  1. What was the operation?
  2. What was the first number?
  3. What was the second number?

What was the operation?

Somehow we need to register that a certain operation type was selected. And for that we need to know what operation types are available. One way to implement this is to create an enumeration type (or user defined scalar type) that contains all valid operations.

pascal
  { All supported operations for our calculator }
  TOperationType = (otNone, otPlus, otMinus, otMultiply, otDivide);

  { TForm1 }

  TForm1 = class(TForm)
pascal
  private
    { private declarations }
    SelectedOperation: TOperationType;
    procedure AddDigit(const pDigit: byte);

What was the first number?

To temporarily store the first number that was entered we need a variable.

pascal
  private
    { private declarations }
    SelectedOperation: TOperationType;
    FirstNumber: longint;
    procedure AddDigit(const pDigit: byte);

What was the second number?

What's on your mind

Now it's time to implement the actions for the function buttons: add, subtract, multiply and divide. Let's start with the '+' button. As mentioned in one of the previous sections: when the '+' button is pressed, we need to store the first number and the operation type. So that's what we are going to do.

Hold on! Before adding all the code here and doing the same for the three other operation buttons, remember what was said when the digit buttons 0..9 were added: do not add redundant code! It's reasonable to assume that the code for the other three operation buttons will be the same as for the '+' button, except for the operation itself. So let's save ourselves some work.

pascal
  private
    { private declarations }
    SelectedOperation: TOperationType;
    FirstNumber: longint;
    SecondNumber: longint;
    procedure AddDigit(const pDigit: byte);
    procedure StoreOperation(const pOperation: TOperationType);

The StoreOperation procedure must do two things: store the operation and store the number that was entered in the display, so it can be used afterwards.

pascal
procedure TForm1.StoreOperation(const pOperation: TOperationType);
begin
  // Store the operation so it can be used later
  SelectedOperation := pOperation;

  // Store the number that was entered by the user
  FirstNumber := StrToInt(edDisplay.Text);
end;

Ok, now back to the '+' button:

Now test the program and see what happens:

What happens is that after pressing the '+' button, or any other operation button for that matter, the display is not cleared. We must find a way to make sure that the display is cleared, as soon as an operation button is pressed. Because we have used procedures to group similar actions, this again is an easy change.

pascal
  private
    { private declarations }
    SelectedOperation: TOperationType;
    FirstNumber: longint;
    SecondNumber: longint;
    doClearDisplay: boolean;
    procedure AddDigit(const pDigit: byte);
    procedure StoreOperation(const pOperation: TOperationType);
pascal
procedure TForm1.StoreOperation(const pOperation: TOperationType);
begin
  // Store the operation so it can be used later
  SelectedOperation := pOperation;

  // Store the number that was entered by the user
  FirstNumber := StrToInt(edDisplay.Text);

  // The display must start with a new number
  doClearDisplay := true;
end;
pascal
procedure TForm1.AddDigit(const pDigit: byte);
begin
  // Must the display be cleared first?
  if doClearDisplay then
  begin
    edDisplay.Text := '0';   // Reset the display to zero
    doClearDisplay := false; // Once is enough...
  end;

  // Limit the number of digits
  if length(edDisplay.Text) < 8 then
  begin
    // Suppress leading zeroes when adding digits
    if edDisplay.Text = '0' then
      edDisplay.Text := IntToStr(pDigit)
    else
      edDisplay.Text := edDisplay.Text + IntToStr(pDigit)
  end;
end;

Now let's see what happens:

We're almost there: we can enter numbers and select an operation. Now it's time to do the actual calculations.

Doing the math

Now that we have stored a number and an operation, it's time to do the actual calculations. Let's start easy with additions.

pascal
procedure TForm1.btnCalculateClick(Sender: TObject);
var result: longint;
begin
  case SelectedOperation of
    otPlus: begin
              // Retrieve the second number
              SecondNumber := StrToInt(edDisplay.Text);
              // Do the math
              result := FirstNumber + SecondNumber;
              // Display the resulting value
              edDisplay.Text := IntToStr(result);
            end;
  end;
end;

The above code is pretty straightforward: if the user presses the '+' button, the first and second number are added up and the result is stored in the edit control on screen. It's good to note that the code uses the case of switch control structure.

We now have a working calculator (that can only add two numbers):

We now could add the 3 missing operations ('-', '*' and '/'). But hold on, there is room for improvement. Let's have a look at the following statement: SecondNumber := StrToInt(edDisplay.Text); We have seen such a statement before: the StoreOperation procedure contains something similar: FirstNumber := StrToInt(edDisplay.Text); Calculating the number the user entered now happens in two different locations. We do not want to repeat ourselves so it's a good idea to create a new function that does the calculation.

pascal
  private
    { private declarations }
    SelectedOperation: TOperationType;
    FirstNumber: longint;
    SecondNumber: longint;
    doClearDisplay: boolean;
    procedure AddDigit(const pDigit: byte);
    procedure StoreOperation(const pOperation: TOperationType);
    function GetDisplayValue: longint;
pascal
function TForm1.GetDisplayValue: longint;
begin
  result := StrToInt(edDisplay.Text);
end;

So much for refactoring, back to the calculations.

Now look at the following statements:

pascal
              // Retrieve the second number
              SecondNumber := GetDisplayValue;
              // Do the math
              result := FirstNumber + SecondNumber;

Variable SecondNumber is used to store the value in the display box. However it is not really necessary. The above code can be simplified:

pascal
              // Do the math
              result := FirstNumber + GetDisplayValue;

Now look at the following statements:

pascal
              // Do the math
              result := FirstNumber + GetDisplayValue;
              // Display the resulting value
              edDisplay.Text := IntToStr(result);

The same now applies to the result variable. The above code can be simplified to:

pascal
              // Display the resulting value
              edDisplay.Text := IntToStr(FirstNumber + GetDisplayValue);

Now we can add the 3 remaining operations.

pascal
procedure TForm1.btnCalculateClick(Sender: TObject);
begin
  case SelectedOperation of
    otPlus     : edDisplay.Text := IntToStr(FirstNumber + GetDisplayValue);
    otMinus    : edDisplay.Text := IntToStr(FirstNumber - GetDisplayValue);
    otMultiply : edDisplay.Text := IntToStr(FirstNumber * GetDisplayValue);
    otDivide   : edDisplay.Text := IntToStr(FirstNumber div GetDisplayValue);
  end;
end;

We now have a working calculator for all 4 operations:

Intermezzo

After all this work we now have a useable calculator. But some things are not quite right. The obvious thing to try is dividing a number by zero. And the buttons 'C' and '+/-' don't work yet. These things will be addressed in the next section.

First let's add another procedure, just for the fun of it (well, there's more to it of course:-)):

pascal
  private
    { private declarations }
    SelectedOperation: TOperationType;
    FirstNumber: longint;
    SecondNumber: longint;
    doClearDisplay: boolean;
    procedure AddDigit(const pDigit: byte);
    procedure StoreOperation(const pOperation: TOperationType);
    function GetDisplayValue: longint;
    procedure SetDisplayValue(const pValue: longint);
pascal
procedure TForm1.SetDisplayValue(const pValue: longint);
begin
  edDisplay.Text := IntToStr(pValue);
end;

The above code should look pretty familiar. Have a look at the procedure that does all calculations:

pascal
procedure TForm1.btnCalculateClick(Sender: TObject);
begin
  case SelectedOperation of
    otPlus     : edDisplay.Text := IntToStr(FirstNumber + GetDisplayValue);
    otMinus    : edDisplay.Text := IntToStr(FirstNumber - GetDisplayValue);
    otMultiply : edDisplay.Text := IntToStr(FirstNumber * GetDisplayValue);
    otDivide   : edDisplay.Text := IntToStr(FirstNumber div GetDisplayValue);
  end;
end;

This procedure can now be simplified.

pascal
procedure TForm1.btnCalculateClick(Sender: TObject);
begin
  case SelectedOperation of
    otPlus     : SetDisplayValue(FirstNumber + GetDisplayValue);
    otMinus    : SetDisplayValue(FirstNumber - GetDisplayValue);
    otMultiply : SetDisplayValue(FirstNumber * GetDisplayValue);
    otDivide   : SetDisplayValue(FirstNumber div GetDisplayValue);
  end;
end;

Loose ends

There's a couple of things that need to be done: implement the two loose buttons and make the calculator a bit more robust.

The +/- button

pascal
procedure TForm1.btnPlusMinusClick(Sender: TObject);
begin
  SetDisplayValue(0 - GetDisplayValue);
end;

See here the fruits of our labor. We have reused the procedure SetDisplayValue and GetDisplayValue to implement the negate function.

Try it by running the program and press the '+/-' button.

The Clear button

pascal
procedure TForm1.btnClearClick(Sender: TObject);
begin
  SetDisplayValue(0);          // Start from scratch
  SelectedOperation := otNone; // No operation selected yet
  doClearDisplay := false;     // The display is already cleared
end;

The above code is pretty self-explanatory: the display is cleared (the first line), we 'forget' about any pending operation by clearing the SelectedOperation variable and there is no need to clear the display when adding new digits, because it was already cleared by the first statement.

Divide by zero

Let's go crazy: run the application and try to divide 10 by 0. This will make the application crash horribly. We have to make sure that this will not happen. The place to check this of course is the place where all calculations are performed (TForm1.btnCalculateClick).

pascal
procedure TForm1.btnCalculateClick(Sender: TObject);
begin
  case SelectedOperation of
    otPlus     : SetDisplayValue(FirstNumber + GetDisplayValue);
    otMinus    : SetDisplayValue(FirstNumber - GetDisplayValue);
    otMultiply : SetDisplayValue(FirstNumber * GetDisplayValue);
    otDivide   : begin
                   if GetDisplayValue <> 0 then
                     SetDisplayValue(FirstNumber div GetDisplayValue)
                   else
                     begin
                       // Display an error message to the user
                       MessageDlg('It is not possible to divide a number by 0!', mtWarning, [mbCancel],0);
                       // Reset the calculator to start with a clean slate
                       btnClearClick(nil);
                     end
                 end
  end;
end;

Things to note:

  1. MessageDlg is a function for displaying a short warning/error/informative message to the user. ShowMessage can also be used. It is a bit easier to use but cannot display warning/error icons.
  2. btnClearClick(nil): as soon as an error condition occurs we must reset the calculator. That's basically the same as pressing the 'C' button. We simulate pressing the 'C' button by directly calling the event handler.

Overflows

Now two things could have happened:

  1. The application gives an incorrect result (something like 1674919425).
  2. The application raises an error.

If it's the first option then overflow errors have been disabled for the project. Enable them by ticking the Overflow option box:

Now run the program again and see what happens with overflows.

If it was the second (and expected) option then this means we have to add exception handling to our little calculator. Exception handling is used to prevent an application from crashing when errors occur. In our case we want to handle the arithmetic overflow error that might occur. Because all calculations are done in one place, it's easy to catch any overflow errors.

pascal
procedure TForm1.btnCalculateClick(Sender: TObject);
begin
  // Catch any overflow errors
  try
    case SelectedOperation of
      otPlus     : SetDisplayValue(FirstNumber + GetDisplayValue);
      otMinus    : SetDisplayValue(FirstNumber - GetDisplayValue);
      otMultiply : SetDisplayValue(FirstNumber * GetDisplayValue);
      otDivide   : begin
                     if GetDisplayValue <> 0 then
                       SetDisplayValue(FirstNumber div GetDisplayValue)
                     else
                       begin
                         // Display an error message to the user
                         MessageDlg('It is not possible to divide a number by 0!', mtWarning, [mbCancel],0);
                         // Reset the calculator to start with a clean slate
                         btnClearClick(nil);
                       end
                   end
    end;
  except
    on E: EIntOverflow do
      begin
        // Display an error message
        MessageDlg('The result of the calculation was too big for the calculator to process!', mtWarning, [mbCancel], 0);
        // Reset the calculator
        btnClearClick(nil);
      end
  end
end;

Note that even with the exception handling in place, the application will still halt when run from inside the IDE. However the application is only paused and still active. Press F9 to continue. This will display another pop up window, a debugger notification window. Press Continue. Now our own exception handler will kick in with the expected message.If you were to run the application stand alone (i.e. outside the IDE) then you would only see the message box that we added to the exception handler.

Final tweaks

Remember that at a certain point a variable called SecondNumber was introduced. If you choose Run/Build All from the menu, then after building the application the compiler will display a message in the Messages window that this particular variable is never used. If you click on the message text the IDE opens the exact location in the editor where the variable is declared.

As soon as our demo Calculator is started we see that the number 0 in the display has the focus (see image below).

This is counter intuitive because a user should not be able to enter anything in that box. Even worse as soon as she would type something in there that is not a number, our calculator would crash! So it's better not to give access to the that control at all. We are going to fix that.

Run the program to see the result of these changes.

(Under construction: OO-ify the program)


From the Free Pascal wiki, page "Howdy World (Hello World on steroids)", as it stood on 2022-08-06 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 2, last changed by WikiArchive .