Associative Arrays

Associative arrays (also known as maps or dictionaries) use keys instead of numeric indices to store and retrieve values. In DWScript, these are highly efficient and built directly into the language.

Declaration & Initialization

Use the array[KeyType] of ValueType syntax. Strings are the most common key type, but other ordinal types like Integers or Enumerations can also be used.

var capitals : array[String] of String;

// Assigning values
capitals['France'] := 'Paris';
capitals['Japan'] := 'Tokyo';
capitals['USA'] := 'Washington D.C.';

// Accessing
PrintLn('The capital of France is ' + capitals['France']);
Result
The capital of France is Paris

Operators

The in and not in operators provide a clean way to check if a key exists in the array.

var capitals : array[String] of String;
capitals['Germany'] := 'Berlin';

if 'Germany' in capitals then
  PrintLn('Germany is in the list')
else
  PrintLn('Germany is missing');
Result
Germany is in the list

Methods

Associative arrays support several built-in methods for management and inspection.

Method Description
Count / Length Returns the number of key-value pairs.
Keys Returns a dynamic array containing all keys.
Delete(key) Removes the entry for the specified key. Returns True if found.
Clear Removes all entries from the array.
var capitals : array[String] of String;
capitals['France'] := 'Paris';

PrintLn('Count: ' + IntToStr(capitals.Count));

capitals.Delete('USA');
Result
Count: 1

Iterating

You can use a for..in loop on the array's Keys to iterate through the entries. Direct iteration over an associative array is not supported.

var capitals : array[String] of String;
capitals['France'] := 'Paris';
capitals['Japan'] := 'Tokyo';

// Iterating keys and accessing values
var keys := capitals.Keys;
keys.Sort;
for var country in keys do
  PrintLn(country + ' -> ' + capitals[country]);
Result
France -> Paris
Japan -> Tokyo
On this page