I have the following:
TDirection = (dirNorth, dirEast, dirSouth, dirWest);
TDirections = set of TDirection;
In a seperate class I have it declared as a property:
property Directions: TDirections read FDirections write FDirections;
What I want is to be able to treat them as if they were Booleans, so for example if dirNorth
was True then it would be 1
, if False it would be 0
.
I am trying to imagine it as (1,0,0,0)
I think to check if a direction is True, I could use:
var
IsTrue: Boolean;
begin
IsTrue := (DirNorth in Directions);
Not sure if the above is correct or not, but then my other problem is how to change one of the directions to True
or False
?
I have now reached one of my confusion states :(
This is the last thing I tried to set the value but I am getting Illegal Expression (in Lazarus).
Directions(TDirection(DirNorth)) := True;
Directions
is a set of elements of type TDirection
.
To see if it contains dirNorth
, do dirNorth in Directions
. The result of using the in
operator is a boolean; dirNorth in Directions
is true iff the set Directions
contains the element dirNorth
.
To make sure dirNorth
is included in Directions
, do Directions := Directions + [dirNorth]
.
To make sure dirNorth
is not included in Directions
, do Directions := Directions - [dirNorth]
.
To set Directions
to a particular value, simply assign: Directions := [dirNorth, dirSouth]
.
Formally, +
computes the union of two sets; -
computes the set difference of two sets. *
computes the intersection of the two operands.
You also have the nice Include
and Exclude
functions: Include(Directions, dirNorth)
does the same thing as Directions := Directions + [dirNorth]
; Exclude(Directions, dirNorth)
does the same thing as Directions := Directions - [dirNorth]
.
For example, if
type
TAnimal = (aDog, aCat, aRat, aRabbit);
TAnimalSet = set of TAnimal;
const
MyAnimals = [aDog, aRat, aRabbit];
YourAnimals = [aDog, aCat];
then
aDog in MyAnimals = true;
aCat in MyAnimals = false;
aRat in YourAnimals = false;
aCat in YourAnimals = true;
MyAnimals + YourAnimals = [aDog, aRat, aRabbit, aCat];
MyAnimals - YourAnimals = [aRat, aRabbit];
MyAnimals * YourAnimals = [aDog];
Implicit in my answer is the fact that the Delphi set
type is modelled after the mathematical set. For more information about the Delphi set
type, please refer to the official documentation.