Program Structure

Understanding how to organize your code into units and use them is fundamental to building scalable applications in DWScript.

Scripts vs Units

DWScript code can be organized as standalone scripts or reusable units.

  • Scripts: A linear sequence of instructions, typically used for main entry points or simple tasks.
  • Units: Collections of types, variables, and functions that can be imported by other scripts or units.

Unit Syntax

A unit consists of an interface section (public API) and an implementation section (internal logic).

unit MyMath;

interface

// Public declarations
function Add(a, b : Integer) : Integer;

implementation

// Internal implementation
function Add(a, b : Integer) : Integer;
begin
  Result := a + b;
end;

end.

Unit Lifecycle

Units can optionally include initialization and finalization blocks:

  • initialization: Runs once when the unit is first loaded, before the main script starts. Used for setting up global state or caches.
  • finalization: Runs when the script execution ends. Used for cleaning up resources.

Uses Clause

To use code from another unit, you must include it in the uses clause. This can appear in the main script or within a unit's interface/implementation sections.

program MyApp;

// Import the 'MyMath' unit
uses MyMath;

var sum := Add(10, 20);
PrintLn(sum);

Unit Namespaces

While DWScript supports dotted unit names for organization, it also features a unique unit namespace construct. This allows you to aggregate multiple existing units into a single identifier, making it easier to manage large libraries.

Creating a Namespace

A namespace unit uses the unit namespace keywords and a uses clause to list the units it aggregates.

unit namespace MyLibrary;

uses 
  MyLibrary.Core, 
  MyLibrary.Utils;

Using a Namespace

When a script uses the namespace unit, all public symbols from the aggregated units become available directly.

uses MyLibrary;

// Symbols from Core and Utils are now available
// without needing to import them individually.
var result := Process(FetchData);
On this page