[fpc-pascal] Sample unit code

Pete Cervasio cervasio at airmail.net
Sat Apr 4 20:46:58 CEST 2009


On Saturday 04 April 2009 11:40:03 Francisco Reyes wrote:
>
> I guess I could try one unit at a time until I find a simple one, but I
> figure if anyone knows of a simple unit that may be easy to read, that may
> be a better starting point.

Here's a simple unit that may help.  I have occasion to add time values in my 
programs.  I don't care that 249 seconds isn't "proper time" and in the form 
of 4 minutes and 9 seconds, I just want it encoded into a TDateTime value so 
I can add it to another TDateTime value.

Save this as my_unit.pp:

unit my_unit;

interface

{ Everything out here in the interface section is seen by programs
  that use this unit }

function EncodeTimeValue (hr, min, sec, msec: Integer): TDateTime;

implementation

{ Everything down here is hidden to the outside }

const
  HoursPerDay = 24;
  MinutesPerDay = 60 * HoursPerDay;
  SecondsPerDay = 60 * MinutesPerDay;
  MilliSecsPerDay = 1000 * SecondsPerDay;

function EncodeTimeValue (hr, min, sec, msec: Integer): TDateTime;
begin
  Result := hr / HoursPerDay + 
            min / MinutesPerDay +
            sec / SecondsPerDay +
            msec / MilliSecsPerDay;
end;

end.

There you go, one complete unit.  In a main program (or even in another unit), 
all you have to do is use that unit and you can then call the function all 
you want:

program test_my_unit;

uses
  my_unit;

begin
   Writeln ('24 hours and 720 minutes is 1.5 days: ',
             EncodeTimeValue (24, 720, 0, 0));
   { Uncomment this next to see an error, because HoursPerDay is private }
   { Writeln ('Hours per day is: ', HoursPerDay); }
end.

To add a new routine, put it down in the implementation section, and copy 
the 'procedure foo(blahblah)' or 'function bar(blahblah): blah' part up to 
the interface section.

There are also 'initialization' and 'finalization' sections too, but you can 
probably ignore those until you understand units better.  

I hope this is helpful.  The code above is released to the public domain, if 
anyone cares to use it.

Best regards,
Pete C.

-- 
=====================================================================
Cliches are a dime a dozen; that's why I avoid them like the plague.
=====================================================================



More information about the fpc-pascal mailing list