Free Pascal Language Reference – Complete Guide

Last update: 29th September 2025
  • Free Pascal: Free, Delphi-compatible, cross-platform compiler, ideal for modern applications.
  • Lazarus IDE: Visual environment for creating GUIs, keyboard shortcuts that accelerate development and debugging.
  • Syntax and key features: types, flow control, object-oriented programming, file, array, and record handling.
  • Best practices and robustness: exception handling (try/except/finally) and use of debugging tools for maintainable code.
Free Pascal Language Reference

Welcome to the article Free Pascal Language Reference – Complete GuideIn today's digital age, mastery of a programming language is an invaluable skill, and Free Pascal is an option that combines simplicity with great computing power.

This article serves as a comprehensive and detailed guide covering everything from the very basics to advanced concepts of the Free Pascal language. Whether you are a beginner looking to learn a new language, an educator looking for a teaching resource, or an experienced programmer looking to brush up on your knowledge, you will find everything you need here. The content is organized into different sections and appendices for quick and effective reference.

Free Pascal is an open-source compiler for the Pascal programming language, which was originally developed by Niklaus Wirth. This compiler supports multiple architectures and operating systems, and is compatible with Delphi, a version of Pascal developed by Borland. Free Pascal makes it easy to create applications by taking a modern and versatile approach to the classic Pascal language.

1: Common Hotkeys in Lazarus IDE

Command Hotkey
Compile F9
Run F9 (if already compiled)
Stop F2
Step by step F8
Step by step (enter) F7
Step by step (exit) Shift + F8
Continue F9
Show/Hide windows F12
Navigate back Alt + Left Arrow
Navigate forward Alt + Right Arrow
Cut Ctrl + X
Copy Ctrl + C
Take Ctrl + V
Undo Ctrl + Z
Redo Ctrl + Y
Search Ctrl + F
find next F3
Search previous Shift + F3
Replace Ctrl + R
Open file Ctrl + O
Save File Ctrl + S
Save All Ctrl + Shift + S
Close File Ctrl + F4
New Unit Ctrl + Shift + N
New Form Ctrl + N
Help F1

Having these shortcut keys at hand can greatly speed up your workflow in Lazarus, allowing you to be more efficient while you become familiar with the development environment.


2: Reserved Words in Free Pascal

Knowing the reserved words of the Free Pascal language is crucial to avoid compilation errors and better understand how the language works. Here is a table containing the most common reserved words in Free Pascal:

and array as asm begin
CASE​ class const constructor keep on going
destructor div do downto else
end except exit exports false
fillet finalization finally for function
goth if implementation in inherited
initialization online interface is label
against Vittorio Citro Boutique Official Site | Clothing and Footwear Buy the new collection online on Vittoriocitro.it Express Shipping and Free Return.Vittorio Citro Boutique Official Store | Fashion items for men and women not object of
on or packed procedures program
property raise record repeat set
shl shr string then to
true try type unit until
uses var while with xor

3: Free Pascal Language Reference. Quick Start Guide.

This appendix provides an overview of the features and syntax of the Free Pascal programming language. It is designed to be a quick and handy reference for students who want to learn the basics of Free Pascal.

Index of Topics:

1. Introduction to Free Pascal

  • Goal: Understand what Free Pascal is and its relevance.
  • Definition: Free Pascal is an open source compiler for the Pascal programming language.
  • Example: N/A

2. Hello World

  • Goal: Write and understand your first program in Free Pascal.
  • Definition: A simple program that displays a message to the console.
  • Example:
    program HelloWorld;
    begin
      WriteLn('Hello, World!');
    end.
    

3. Variables and Data Types

  • Goal: Understand data types and how to use variables.
  • Definition: Variables are spaces in memory where data is stored that can change during the execution of the program.
  • Example:
    var
      myInt: Integer;
      myString: String;
    begin
      myInt := 10;
      myString := 'Hola';
    end.
    

4. Arithmetic Operators

  • Goal: Get familiar with basic arithmetic operators.
  • DefinitionArithmetic operators perform basic numerical calculations.
  • Example:
    var
      sum, diff: Integer;
    begin
      sum := 10 + 5;  // Suma
      diff := 10 - 5; // Resta
    end.
    

5. Flow Control: IF…ELSE

  • Goal: Understanding the use of conditions in Free Pascal.
  • Definition: The statement IF...ELSE It is used to execute blocks of code based on a condition.
  • Example:
    var
      x: Integer;
    begin
      x := 10;
      if x > 5 then
        WriteLn('x es mayor que 5')
      else
        WriteLn('x no es mayor que 5');
    end.
    

6. Flow Control: FOR Loop

  • Goal: Understand how to use FOR loops to repeat tasks.
  • Definition: The loop FOR It is used to repeat a block of code a specified number of times.
  • Example:
    var
      i: Integer;
    begin
      for i := 1 to 5 do
        WriteLn(i);
    end.
    

7. Flow Control: WHILE Loop

  • Goal: Learn how to use WHILE loops.
  • Definition: The loop WHILE It is used to repeat a block of code as long as a condition is met.
  • Example:
    var
      i: Integer;
    begin
      i := 1;
      while i <= 5 do
      begin
        WriteLn(i);
        Inc(i);
      end;
    end.
    

8. Functions and Procedures

  • Goal: Learn to modularize code using functions and procedures.
  • Definition: Functions and procedures are reusable blocks of code. Functions return a value, while procedures do not.
  • Example:
    procedure SayHello;
    begin
      WriteLn('Hello!');
    end;
    
    function Add(a, b: Integer): Integer;
    begin
      Result := a + b;
    end;
    
    begin
      SayHello;
      WriteLn(Add(3, 4));  // Output: 7
    end.
    

9. Arrays

  • Goal: Understand how arrays are used to store multiple values.
  • Definition: An array is an ordered collection of elements of the same type.
  • Example:
    var
      numbers: array[1..5] of Integer;
    begin
      numbers[1] := 1;
      numbers[2] := 2;
      // ... y así sucesivamente
    end.
    

10. Records

  • Goal: Learn how to define and use records to group related variables.
  • Definition: A record is a composite data type that can contain variables of different types.
  • Example:
    type
      Student = record
        name: String;
        age: Integer;
      end;
    
    var
      student1: Student;
    begin
      student1.name := 'John';
      student1.age := 20;
    end.
    

11. Error Handling with TRY…EXCEPT

  • Goal: Learning to handle errors in Free Pascal.
  • Definition: TRY...EXCEPT It is used to catch and handle exceptions or errors in code.
  • Example:
    var
      x, y, result: Integer;
    begin
      x := 10;
      y := 0;
      try
        result := x div y;
      except
        WriteLn('No se puede dividir entre cero.');
      end;
    end.
    

12. Handling Text Files

  • Goal: Learn to read and write text files in Free Pascal.
  • Definition: Text files are used to store data in text form.
  • Example:
    var
      myFile: Text;
    begin
      Assign(myFile, 'example.txt');
      Rewrite(myFile);
      WriteLn(myFile, 'Hello, file!');
      Close(myFile);
    end.
    

13. Handling Binary Files

  • Goal: Understand how to work with binary files.
  • DefinitionBinary files are used to store data in a format that is readable by computers but not necessarily by humans.
  • Example:
    var
      myFile: File of Integer;
      x: Integer;
    begin
      Assign(myFile, 'example.bin');
      Rewrite(myFile);
      x := 42;
      Write(myFile, x);
      Close(myFile);
    end.
    

14. INI files

  • Goal: Learn how to use INI configuration files.
  • Definition: INI files are text files used to save settings.
  • Example:
    // Usando la biblioteca TIniFile
    var
      Ini: TIniFile;
    begin
      Ini := TIniFile.Create('config.ini');
      Ini.WriteString('General', 'Name', 'John');
      Ini.Free;
    end.
    

15. Databases with SQLite

  • Goal: Learn to work with SQLite databases.
  • Definition: SQLite is a database management system that easily integrates into a variety of applications.
  • Example:
    // Conexión y consulta usando SQLite (asumiendo que ya está integrado)
    var
      conn: TSQLite3Connection;
    begin
      conn := TSQLite3Connection.Create(nil);
      conn.DatabaseName := 'example.db';
      conn.Open;
      // ... Realizar consultas SQL
      conn.Close;
    end.
    

16. ZeosLib and Databases

  • Goal: Learn how to use ZeosLib to connect to multiple databases.
  • Definition: ZeosLib is a library that allows you to connect to different database systems.
  • Example:
    // Conexión usando ZeosLib (asumiendo que ya está integrado)
    var
      conn: TZConnection;
    begin
      conn := TZConnection.Create(nil);
      conn.Protocol := 'sqlite-3';
      conn.Database := 'example.db';
      conn.Connect;
      // ... Realizar consultas SQL
      conn.Disconnect;
    end.
    

17. Object Oriented Programming: Classes and Objects

  • Goal: Understand the basics of object-oriented programming (OOP) in Free Pascal.
  • DefinitionIn OOP, classes are templates used to create objects. Objects are instances of classes.
  • Example:
    type
      TCar = class
        Speed: Integer;
        procedure Accelerate;
      end;
    
    procedure TCar.Accelerate;
    begin
      Inc(Speed, 10);
    end;
    
    var
      myCar: TCar;
    begin
      myCar := TCar.Create;
      myCar.Accelerate;
      // ...
    end.
    

18. String Manipulation

  • Goal: Learn the basic functions for manipulating text strings.
  • Definition: Free Pascal offers several functions for manipulating text strings.
  • Example:
    var
      s: String;
    begin
      s := 'Hello, World!';
      WriteLn(Length(s));  // Devuelve la longitud de la cadena
      WriteLn(Copy(s, 1, 5));  // Devuelve una subcadena
    end.
    

19. Using Lists and Collections

  • Goal: Get familiar with more advanced data structures such as lists.
  • Definition: Lists are data structures that can contain multiple elements.
  • Example:
    var
      myList: TList;
      x: Pointer;
    begin
      myList := TList.Create;
      // ... (Agregar y eliminar elementos)
      myList.Free;
    end.
    

20. Graphical Interfaces with Lazarus

  • Goal: Learn to create applications with graphical interfaces using Lazarus.
  • Definition: Lazarus offers an easy way to create graphical user interfaces (GUI) through a visual designer.
  • Example: N/A (This topic is easier to understand with visual demonstrations.)
  What is Java: Complete Introduction to the Programming Language

21. Connecting to MySQL using ZeosLib

  • Goal: Learn how to connect a Free Pascal/Lazarus application to a MySQL database using ZeosLib.
  • Definition: ZeosLib also allows connection to MySQL databases.
  • Example:
    var
      conn: TZConnection;
    begin
      conn := TZConnection.Create(nil);
      conn.Protocol := 'mysql';
      conn.HostName := 'localhost';
      conn.Database := 'mydb';
      conn.User := 'root';
      conn.Password := 'password';
      conn.Connect;
      // ... Realizar consultas SQL
      conn.Disconnect;
    end.
    

22. Form Management in Lazarus

  • Goal: Understand how to create and manage forms in Lazarus applications.
  • DefinitionA form is a window in a GUI application that contains other controls such as buttons, text boxes, etc.
  • Example: N/A (This topic is easier to understand with visual demonstrations.)

23. Structure of a Lazarus Project

  • Goal: Understand the basic structure of a Lazarus project file (.lpr).
  • Definition: A .lpr file is the entry point for a Lazarus application. This file contains the routine main which starts the application.
  • Example:
    program MyLazarusProject;
    
    uses
      Forms,
      Unit1;  { Formulario principal }
    
    {$R *.res}
    
    begin
      Application.Initialize;
      Application.CreateForm(TForm1, Form1);
      Application.Run;
    end.
    

24. Structure of a Form in Lazarus

  • Goal: Learn the basic structure of a form file (.lfm) and its associated source code file (.pas).
  • Definition: .lfm files contain the description of the user interface. The associated .pas files contain the code that handles the logic of the form.
  • Example (.lfm):
    object Form1: TForm1
      Caption = 'My Form'
      // Propiedades adicionales aquí
      object Button1: TButton
        Caption = 'Click Me'
        // Propiedades adicionales aquí
      end;
    end;
    
  • Example (.pas):
    unit Unit1;
    
    {$mode objfpc}{$H+}
    
    interface
    
    uses
      Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls;
    
    type
      TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        // Declaraciones privadas
      public
        // Declaraciones públicas
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.lfm}
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      ShowMessage('Hello, World!');
    end;
    
    end.
    

25. Basic Sections of a .pas File in Lazarus

  • Goal: Understanding where to place const, var, uses, procedures and other elements.
  • Definition: A .pas file is made up of several sections such as interface, implementation, uses, var, const, type, and procedures and functions.
  • Example:
    unit MyUnit;
    
    interface
    
    uses
      Classes, SysUtils;
    
    const
      MyConst = 42;
    
    type
      TMyClass = class
      end;
    
    var
      MyVar: Integer;
    
    procedure MyProcedure;
    
    implementation
    
    procedure MyProcedure;
    begin
      // Código aquí
    end;
    
    end.
    

26. Debugging and Code Debugging

  • Goal: Learn how to use the built-in debugging tools in Lazarus.
  • Definition: Debugging is the process of finding and correcting errors in code.
  • Example: N/A (It is best to demonstrate debugging capabilities within the Lazarus IDE.)
  All about Tkinter: the library for graphical interfaces in Python

27. Use of Third Party Components

  • Goal: Learn how to integrate third-party components and libraries into a Lazarus project.
  • DefinitionThird-party components are libraries or controls that are not included with Lazarus but add additional functionality.
  • Example: N/A (The process varies depending on the component).

28. Working with Events

  • Goal: Understand event handling in Lazarus applications.
  • Definition: Events are actions that are triggered in response to some activity, such as a mouse click or a key press.
  • Example:
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      ShowMessage('Button clicked');
    end;
    

29. Creating Multiplatform Projects

  • Goal: Learn how to configure a project in Lazarus to be cross-platform.
  • DefinitionA cross-platform project is one that can be compiled and run on multiple operating systems without significant code changes.
  • Example: N/A (This is more of a project configuration than a code example.)

30. Multimedia File and Resource Management

  • Goal: Understand how to manage resources such as images, sounds, etc., in a Lazarus application.
  • Definition: Resources are additional files that an application needs to function properly.
  • Example:
    Image1.Picture.LoadFromFile('image.jpg');
    

31. Working with Threads (Threading)

  • Goal: Understand the basics of working with multiple threads in Free Pascal.
  • DefinitionThreads allow an application to perform multiple tasks at the same time.
  • Example:
    type
      TMyThread = class(TThread)
      protected
        procedure Execute; override;
      end;
    
    procedure TMyThread.Execute;
    begin
      // Código para el hilo aquí
    end;
    

32. Internationalization and Localization

  • Goal: Learn how to prepare an application for multiple languages.
  • DefinitionInternationalization is the process of preparing an application for translation into multiple languages.
  • Example: N/A (Normally additional resource files or libraries are used for this.)

4: Exception Handling in Free Pascal and Lazarus

Goal

Understand how to handle errors and exceptions in Free Pascal using the keywords try, except, and finally.

What is Exception Management?

Exception handling is a mechanism for handling runtime errors that may occur in a program. This is crucial for building robust and reliable applications. Free Pascal provides an exception handling system similar to other programming languages, which includes the keywords try, except, and finally.

Basic Structure

The basic structure for handling exceptions looks like this:

try
  // Código que podría causar una excepción
except
  on E: Exception do
  begin
    // Código para manejar la excepción
  end;
end;

Use of try y except

try y except are used to catch and handle exceptions. Code that might throw an exception is placed inside the block try, and the code to handle the exception is placed in the block except.

program ExceptionExample;
uses SysUtils;

var
  A, B, Result: Integer;

begin
  A := 10;
  B := 0;
  
  try
    Result := A div B; // Esto lanzará una excepción porque B es 0
  except
    on E: EDivByZero do
    begin
      WriteLn('Error: ' + E.Message);
    end;
  end;
end.

Use of finally

The clause finally is used to execute a block of code regardless of whether an exception has been thrown or not. This block is always executed, making it useful for releasing resources, such as closing files or freeing memory.

program FinallyExample;
uses SysUtils;

var
  MyFile: TextFile;
  FileName: String;

begin
  FileName := 'example.txt';

  try
    AssignFile(MyFile, FileName);
    Reset(MyFile); // Abre el archivo para lectura
    // Leer y procesar el archivo
  finally
    CloseFile(MyFile); // Esto se ejecutará siempre
  end;
end.

Combination of try, except, and finally

It is possible to combine try, except, and finally to handle exceptions and ensure that certain actions are performed regardless of whether an exception is thrown.

program CombinedExample;
uses SysUtils;

var
  A, B, Result: Integer;

begin
  A := 10;
  B := 0;

  try
    try
      Result := A div B; // Esto lanzará una excepción porque B es 0
    except
      on E: EDivByZero do
      begin
        WriteLn('Error: ' + E.Message);
      end;
    end;
  finally
    WriteLn('Esta parte se ejecutará siempre.');
  end;
end.

With this, you should have a good understanding of how to handle exceptions in Free Pascal. It is a powerful tool to make your code more robust and maintainable.

5: Good Programming Practices in Free Pascal and Lazarus

Goal

Understand the importance of following good programming practices to write more readable, maintainable and efficient code.

What are Good Programming Practices?

Good programming practices are a set of rules and guidelines that are followed to improve code quality. They not only make code easier to read and understand, but also make it more reliable and maintainable.

Comments and Documentation

What is a biosimilar

Comments are pieces of text in the source code that are not executed. They serve to explain how the code works and provide additional information that may be useful to the developer.

Example:

// Este es un comentario de una sola línea
{
  Este es un comentario
  de múltiples líneas
}

Best Agricultural Practices

  • Use comments to explain why something is being done, rather than what is being done.
  • Keep your comments up to date; an outdated comment can be more damaging than no comment at all.
  • Avoid obvious comments that do not add value.

Documentation

For larger projects, it is crucial to have more extensive documentation explaining how the program works, how its different parts are used, etc. This documentation can be in a separate file or even in a wiki.

Software Design Principles

DRY (Don't Repeat Yourself)

What is it?

The DRY principle suggests that each piece of knowledge should have a unique, non-repeated representation within a system.

  Learn to Code: 7 Reasons Why You Should Start Today
Example:

Instead of writing the same logic to calculate the area of ​​a circle in multiple places, create a function and reuse it.

function CalculateCircleArea(radius: Double): Double;
begin
  Result := Pi * Sqr(radius);
end;

KISS (Keep It Simple, Stupid)

What is it?

The KISS principle urges keeping the design as simple and unadorned as possible. The simpler the code, the easier it is to understand and maintain.

Example:

Avoid using complicated solutions when a simple one will work just as well.

// En lugar de
if (isTrue = true) then
  // Hacer algo
// Utiliza simplemente
if isTrue then
  // Hacer algo

Other Important Principles

  • YAGNI (You Aren't Gonna Need It): Don't add functionality until you really need it.
  • SOLID PrinciplesThese are five object-oriented design principles that help make code cleaner and more efficient.

With these best practices and principles in mind, you'll be on your way to writing code that not only works well, but is also easy to understand, modify, and maintain.


6: Quick Reference Appendices

Goal

Provide a quick and practical reference for key concepts and elements of the Free Pascal language and the Lazarus IDE.


Table of Operators and their Precedence

It is crucial to understand the order in which operators are executed to avoid errors and unexpected behavior. Below is a table illustrating the precedence of operators in Free Pascal, from highest to lowest.

Precedence Operator Description Example
1 ^ Dereference p^
2 not, -, + Negation, less unary, more unary -a, not b
3 div, mod Integer division, modulus a div b
4 *, / Multiplication, division a * b
5 +, - Addition, subtraction a + b
6 =, <> Equality, inequality a = b
7 <, >, <=, >= Comparison a < b
8 and And logical a and b
9 or Or logical a or b

Glossary of Technical Terms

  • IDE (Integrated Development Environment): Software that provides essential tools for programming.
  • Compiler: Program that transforms the source code into an executable file.
  • Variable: A storage element that holds a value or reference.
  • Constant: A value that does not change during program execution.
  • Function: Block of code designed to perform a specific task.
  • Procedure: Similar to a function, but does not return a value.
  • Array: Data structure containing a series of elements, generally of the same type.
  • Record: Data structure that allows multiple elements, possibly of different types, to be stored under a single name.
  • Pointer: Variable that stores the address of another variable.
  • String: Data type for storing character sequences.
  • Boolean: Type of data it can contain True o False.
  • Integer: Numeric data type that contains integers.
  • Float (Real, Double): Numeric data type that contains numbers with decimals.
  • Exception: Error that occurs during program execution.
  • Debugging: Process of finding and correcting errors in a program.
  • API (Application Programming Interface): Set of functions and procedures that allow the creation of applications.

This glossary and table of operators provide a quick reference for better understanding key terms and elements in Free Pascal and Lazarus. As you become more familiar with programming, these resources will become increasingly useful.

Web Resources on Free Pascal Language Reference

  1. Free Pascal Official Site
    • The official site where you can find all documentation and downloads related to Free Pascal.
  2. Lazarus Official Site
    • The home of Lazarus, the integrated development environment for Free Pascal.
  3. Lazarus Wiki
    • A comprehensive source of tutorials, examples, and solutions to common problems.
  4. Free Pascal and Lazarus on Stack Overflow
    • A place to ask questions and get answers about specific programming problems in Free Pascal and Lazarus.
  5. Lazarus and Free Pascal Community Forum

Free Pascal's Parting Words Language Reference

We hope that this article, “Free Pascal Language Reference – Complete Guide”, has been of great use to you. Our intention has been to provide a comprehensive resource that serves as a primer for all your Free Pascal programming needs. Whether you are a student, a professional, or someone with a casual interest in programming, we know that having a reliable guide is invaluable.

If you found this content useful, we invite you to share it with colleagues, students, and friends who can also benefit from this comprehensive resource. Programming is a constantly evolving field, and we believe that sharing knowledge is the key to growing and moving forward together.

Thank you for taking the time to read and explore this article. Happy programming!

Feel free to share “Free Pascal Language Reference – Complete Guide” on your favorite social networks and programming forums. Your support helps us continue generating high-quality content. See you next time!