Methods & Functions

Break your code into reusable blocks using procedures and functions.

Procedures vs Functions

  • Procedures: Use the procedure keyword. They perform an action but do not return a value.
  • Functions: Use the function keyword. They must return a value by assigning it to the implicit Result variable.
procedure SayHello(name : String);
begin
  PrintLn('Hello ' + name);
end;

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

SayHello('World');
var sum := Add(5, 10);
Result
Hello World

Common Utility Functions

DWScript includes several built-in procedures for common tasks.

Swap

The Swap(var a, b) procedure efficiently exchanges the values of two variables. Both variables must be of the same type.

var x := 10;
var y := 20;
Swap(x, y);
PrintLn(Format('x=%d, y=%d', [x, y]));
Result
x=20, y=10

Parameter Options

Parameters can have different semantics defining how they are passed and evaluated.

Modifier Description
(none) Value: Passed by value (copied).
var Reference: Passed by reference. Changes inside the subroutine affect the original variable.
const Constant: Passed by reference for efficiency (if large), but cannot be modified.
lazy Lazy Evaluation: The expression is passed without being evaluated. It is evaluated every time the parameter is accessed inside the subroutine.

Subroutine Modifiers

Modifiers can be added to the end of a declaration to change its behavior or performance characteristics.

Modifier Description
overload Allows multiple subroutines with the same name but different parameter lists.
inline Hints to the compiler to replace the call with the actual code for better performance.
forward Declares a subroutine that will be implemented later in the same script.
deprecated Marks the subroutine as obsolete, triggering a compiler warning if used.
procedure Process(x : Integer); overload;
begin
  PrintLn('Integer: ' + x.ToString);
end;

procedure Process(s : String); overload;
begin
  PrintLn('String: ' + s);
end;

Process(10);
Process('Hello');
Result
Integer: 10
String: Hello

Advanced Subroutines

For more complex scenarios, see the dedicated page for Parameters & Delegates, which covers:

  • Parameter modifiers (var, const, lazy, out).
  • Default and optional parameters.
  • Procedural types and method pointers (Delegates).
On this page