Difference between revisions of "How to use procedural variables"

From Lazarus wiki
m (How To Use Function Pointers moved to How to use procedural variables: Function pointers are C terminology. No IniCaps in title.)
(-> procvar.)
Line 1: Line 1:
=== These are also known as procedural pointers. ===
+
Copy the text below and it will demonstrate the use of procedural variables, this is a fully 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 23:22, 6 October 2006

Copy the text below and it will demonstrate the use of procedural variables, this is a fully 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;

var
    ptr:Pointer;
    list:Tlist;
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);

//now put a function in an untyped pointer
ptr:=@Hello;
//Type the pointer and call it all at the same time
writeln(TFuncNoArgs_String(ptr));
//A Tlist Example
list:=TList.create;
list.add(@Hello);
writeln(TFuncNoArgs_String(list[0]));
readln;
end.