Difference between revisions of "How to use procedural variables"

From Lazarus wiki
Line 1: Line 1:
 +
=== These are also known as procedural pointers. ===
 +
 +
 
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.
 
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.
  

Revision as of 01:59, 6 October 2006

These are also known as procedural pointers.

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.