How to use procedural variables

From Lazarus wiki
Revision as of 19:18, 5 October 2006 by ChadCrabtree (talk) (How To Use Function Pointers. Demo Program)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Copy the text below and it will demonstrate the use of function pointers, this is a full working program. You don't even need to understand how it works the syntax is pretty simple.


program test;

{$mode objfpc}{$H+} uses

 {$IFDEF UNIX}{$IFDEF UseCThreads}
 cthreads,
 {$ENDIF}{$ENDIF}
 Classes
 { add your units here };

//Make the Types the type corresponds to a function signature type

   TFuncNoArgs_String = function():String;
   TFuncOneArgs_String = function(x:string):string;

//example functions function Hello():String; begin

    result:='Hello There';

end; function Woah(G:String):String; begin

    result:='Woah ' + G;

end;

//overloaded function takes the two types of function //pointers created above procedure Take(f:TFuncNoArgs_String);overload; begin

    writeln(f());

end;

procedure Take(f:TFuncOneArgs_String);overload; begin

    writeln(f('there!!!'));

end;

begin // the "@" symbol turns the variable into a pointer. // This must be done in order pass a function as a // paramater. This also demonstrates that pascal // keeps track of the pointer type so the overloading works!

Take(@Hello); Take(@Woah); readln; end.