Constants

Constants are values that are defined once and cannot be changed during the execution of the script. They are declared using the const keyword.

Declaration

Constants must be assigned a value at the time of declaration. The compiler determines the type of the constant from the value assigned.

const PI = 3.14159;
const APP_NAME = 'My Script';
const MAX_RETRIES = 5;
const DEBUG_MODE = True;

PrintLn(APP_NAME);
Result
My Script

Typed Constants

While DWScript primarily uses untracked constants (which are effectively replaced by their values at compile-time), it also supports typed constants which behave more like read-only variables.

const DEFAULT_TIMEOUT : Integer = 30;

Calculated Constants

Constants can be defined using expressions, provided the expression can be evaluated at compile-time. This often involves using other previously defined constants.

const BASE_VALUE = 100;
const MULTIPLIER = 5;
const CALCULATED = BASE_VALUE * MULTIPLIER; // 500

const GREETING = 'Hello';
const USER = 'Admin';
const WELCOME_MSG = GREETING + ', ' + USER; // "Hello, Admin"

PrintLn(CALCULATED.ToString);
PrintLn(WELCOME_MSG);
Result
500
Hello, Admin

Benefits of Constants

  1. Readability: Meaningful names instead of "magic numbers".
  2. Maintainability: Change a value in one place instead of searching through the entire script.
  3. Performance: Untyped constants are resolved at compile-time, incurring zero runtime overhead.

Built-in Constants

DWScript provides several built-in constants and functions that behave like constants for common mathematical and system values.

  • Pi: The mathematical constant ΓΏ (3.14159...).
  • True, False: Boolean literals.
  • nil: The null pointer/object reference.
PrintLn('The value of Pi is ' + FloatToStr(Pi));
Result
The value of Pi is 3.14159265358979

:::tip While you can define your own constant named PI, it is generally better to use the built-in Pi function for maximum precision. :::

Global vs. Local Constants

Like variables, constants can be declared at the global level or within the scope of a procedure or function.

const GLOBAL_VERSION = '1.0.0';

procedure ShowInfo;
const
  LOCAL_PREFIX = 'VER: ';
begin
  PrintLn(LOCAL_PREFIX + GLOBAL_VERSION);
end;

ShowInfo;
Result
VER: 1.0.0

See Also

On this page