I have the following formula
X := X + F*(1-i div n);
Where
X, F, i, n: integer;
The code I'm using is this
F := 7; // the initial speed with no friction.
n := 10; // the animation number of steps.
Hn := n * 2 ;
X := 0; // first Pos
i := 1;
J := 1;
while J < Hn do
begin
X := X + F * (1 - i div n);
if X > Xmax then X := 0; <-- line (1).
if i >= n then Dec(i)
else Inc(i);
Inc(J);
end;
If it was possible I would like to use this but without class/record implementation(not inside a class/record implementation/method).not the exact syntax, just the same principle, instead of direct assignment to X the SetX is called then the result is assigned to X.
X: integer write SetX; // This is not a correct delphi syntax. I added it to explain the behavior I want.
function SetX(aValue: integer): integer;
const
Xmax: SomeIntegerValue;
begin
if aValue > Xmax then result := 0
else result := aValue;
end;
So I could omit Line (1). If this was possible, all the lines after the formula would be omitted and the while loop would look like this
while J < Hn do // J will be incremented each time the loop wants to read it.
begin
X := X + F * (1 - i div n);
end;
Is there anyway to use the property like behavior?
Note: I'm looking for a way to alter the assignment and reading ways of a variable like you do in a property of a record/class.
You can use local function like
I found a way to do what I wanted. I know that overloading the
:=
operator is not possible, However forcing the compiler to produce the same behavior as the overloaded operator would behave is possible.The overloading would not let me control the LSA (Left Side Argument). but it gave full control to implicitly convert any
TType
(in my case it is aninteger
) toTXinteger
. So all I had to do is make sure that every operator would result in aTType
which will force the compiler to implicitly convert that to aTXinteger
.Forcing the compiler to use my implicit operator every time it wants to assign something to
TXinteger
means I control the assignment Hence I overloaded the:=
operator.the following is a test example that makes omitting Line(1) possible.
Note: for this case it is pointless to do all of this just to omit one line of code. I wanted to share this because it gives an idea of how one could overload the
:=
operator.What I wanted is this:
X:Integer
is read (value read from the variable x's storage).X:Integer
is assigned.by overloading all the operators that use the value of X, I completed the first. And by forcing the compiler as explained above, I completed the second.
Thank you all for your help.
No, property getters and setters can only be implemented in records and classes.