Advertise here.

Tuesday 28 August 2012

Pascal Programming Lesson #12 - Units

We already know that units, such as the crt unit, let you use more procedures and functions than the built-in ones. You can make your own units which have procedures and functions that you have made in them.


To make a unit you need to create new Pascal file which we will call MyUnit.pas. The first line of the file should start with the unit keyword followed by the unit's name. The unit's name and the unit's file name must be exactly the same.

unit MyUnit;

The next line is the interface keyword. After this you must put the names of the procedures that will be made available to the program that will use your unit. For this example we will be making a function calledNewReadln which is like Readln but it lets you limit the amount of characters that can be entered.

unit MyUnit;

interface

function NewReadln(Max: Integer): String;

The next line is implementation. This is where you will type the full code for the procedures and functions. We will also need to use the crt unit to make NewReadln. We end the unit just like a normal program with the endkeyword.

unit MyUnit;

interface

function NewReadln(Max: Integer): String;

implementation

function NewReadln(Max: Integer): String;
var
   s: String;
   c: Char;
begin
   s := '';
   repeat
      c := ReadKey;
      if (c = #8){#8 = BACKSPACE} and (s <> '') then
         begin
            Write(#8+' '+#8);
            delete(s,length(s),1);
         end;
      if (c <> #8) and (c <> #13){#13 = ENTER} and (length(s) < Max) then
         begin
            Write(c);
            s := s + c;
         end;
   until c = #13;
   NewReadln := s;
end;

end.

Once you have saved the unit you must compile it. Now we must make the program that uses the unit that we have just made. This time we will type MyUnit in the uses section and then use the NewReadln function.

program MyProgram;
 
uses
   MyUnit;
 
var
   s: String;
 
begin
   s := NewReadln(10);
end.

0 comments:

Post a Comment