The functions and processes defined in functions and processes are called local functions and processes (subprograms). subprograms are only valid within the parent process.
Next, let's take a look at how to implement the definition and use of a local function and process.
1,CreateApplication.
2,InForm1PlaceMemoComponent (Memo1) And twoButtonComponent (Button1AndButton2).
3,Double-clickButton1Button inButton1clickEnter the following code in the event:
procedure TForm1.Button1Click(Sender: TObject);var X: Integer; {a local procedure} procedure Test; begin Memo1.Lines.Add('Local Function, X = ' + IntToStr(X)); end;begin X := 100; Memo1.Lines.Clear; Memo1.Lines.Add('Main Function, X = ' + IntToStr(X)); Test;end;
4,Double-clickButton2Button inButton2clickEnter the following code in the event:
Procedure tform1.button2click (Sender: tobject); begin test; {because test is defined in button1click, an error is returned.} end;
5,PressCTRL + F9Compile the project and report the following error:Undeclared identifier: 'test'(Undefined identifier)
6,Comment outButton2clickInTestCall the process, re-compile and run, and clickButton1The result is as follows:
Analysis
- The test process is included in the VaR segment of the button1click process. The process declared using this method is a local process, and it is limited to the functions and processes that contain it. A local subroutine can only be called by routines that contain it, but cannot be called in other places of the program. Therefore, test cannot be called during the button2click process.
- An important property of a local process and function is that the variables contained in the process and function are also valid in the local subroutine. The values of the two X variables shown in the preceding example in memo1 are both 100, it indicates that the X variable is not only available in button1click, but can also be used in its subprocess test.
All the above programs are compiled in Delphi7. sample code is downloaded: Local program and process .rar