DWScript provides robust support for enumerations and sets, which are core features for writing clear and type-safe Pascal code.
An enumeration defines a set of named constants. DWScript supports three distinct styles of enumerations.
Symbols are globally scoped within the unit. This is the traditional Pascal style.
type TDirection = (North, East, South, West);
// Type inference
var d1 := North;
// Explicit typing
var d2 : TDirection := North; Using the enum keyword requires you to prefix the values with the type name. This prevents name collisions.
type TStatus = enum (Ready, Busy, Error);
// Type inference
var s1 := TStatus.Ready;
// Explicit typing
var s2 : TStatus := TStatus.Ready; Using the flags keyword automatically assigns power-of-two values (1, 2, 4, 8...). These are designed to be used with bitwise or to combine multiple values.
type TFileAccess = flags (Read, Write, Execute); // 1, 2, 4
// Type inference
var access1 := TFileAccess.Read or TFileAccess.Write;
// Explicit typing
var access2 : TFileAccess := TFileAccess.Read or TFileAccess.Execute; Sets are collections of values from an ordinal type (usually an enumeration). A set can hold any combination of its base type's values, or be empty.
A set of TEnum is stored efficiently as a bitfield. You can even cast a set to an Integer to see its underlying bitmask.
type TCards = (Club, Diamond, Heart, Spade);
type THand = set of TCards;
var hand: THand := [Club, Heart];
if Club in hand then
PrintLn('You have a Club');
// Using ranges in sets
var allMinors: THand := [Club..Diamond];
if Heart in [Club..Spade] then
PrintLn('Hearts are in the range');
hand.Include(Spade);
hand.Exclude(Club);
if hand = [] then
PrintLn('Empty hand'); You have a Club Hearts are in the range
Enumerations and sets provide several built-in methods for convenience:
TMyEnum.Low and TMyEnum.High return the first and last values.TMyEnum.ByName('name') returns the value matching the string.val.Name returns the name of the enumeration value as a string.// Enum ByName
type TDirection = (North, East, South, West);
var dir := TDirection.ByName('South');
PrintLn(dir.Name);
// Set to Integer Cast
type TCards = (Club, Diamond, Heart, Spade);
type THand = set of TCards;
var mySet : THand := [Club, Spade]; // 0th and 3rd bits
PrintLn(Integer(mySet)); South 9
mySet.Include(Value) adds a value to the set.mySet.Exclude(Value) removes a value from the set.mySet.Contains(Value) is equivalent to the in operator.