Learn Pascal Programming Tutorial 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 called NewReadln 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 end keyword.
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.
- Learn Pascal Programming Tutorial Lesson 1 - Introduction to Pascal
- Learn Pascal Programming Tutorial Lesson 2 - Colors, Coordinates, Windows and Sound
- Learn Pascal Programming Tutorial Lesson 3 - Variables and Constants
- Learn Pascal Programming Tutorial Lesson 4 - String Handling and Conversions
- Learn Pascal Programming Tutorial Lesson 5 - Decisions
- Learn Pascal Programming Tutorial Lesson 6 - Loops
- Learn Pascal Programming Tutorial Lesson 7 - Arrays
- Learn Pascal Programming Tutorial Lesson 8 - Types, Records and Sets
- Learn Pascal Programming Tutorial Lesson 9 - Procedures and Functions
- Learn Pascal Programming Tutorial Lesson 10 - Text Files
- Learn Pascal Programming Tutorial Lesson 11 - Data Files
- Learn Pascal Programming Tutorial Lesson 12 - Units
- Learn Pascal Programming Tutorial Lesson 13 - Pointers
- Learn Pascal Programming Tutorial Lesson 14 - Linked Lists
No comments:
Post a Comment