[fpc-pascal] using functions from units & main programme

Sven Barth pascaldragon at googlemail.com
Fri Nov 18 17:55:39 CET 2011


Am 18.11.2011 17:47, schrieb John Lee:
> Sorry for confusion, my email wasn't clear...
> old fpc version, that I have to use because of availability of various
> units...Free Pascal Compiler version 2.2.2 [2008/08/03] for i386
>
> this is jim.pp---
> unit jim;
> interface
>   function fna:string;
>   function fnb:string;
>
> implementation
> function fna:string;
> begin
>   fna:='jim';
> end;
> function fnb:string;
> begin
>   fnb:=fna;
> end;
> end.
>
> this is fred.pp---
> uses jim;
>
> function fna:string;
> begin
>   fna:='fred';
> end;
>
> begin
>   writeln(fnb);
> end.
>
> This writeln gives jim, ie the version in jim - I'd like it to be fred &
> thought that it would! What can I do please, to _force_ fnb to use the
> fred version of fna?

As I said per se this is expected, because the "jnb" in "jim" only knows 
about the "jna" in "jim", but not about the "jna" in your main program.

Possible solution:

Extend your unit "jim" the following way (this is the "function 
variable" approach I mentioned):

=== unit jim begin ===

unit jim;

interface

type
   TStringFunc = function: String;

function fna: String;
function fnb(aFunc: TStringFunc = Nil): String;

implementation

function fna: String;
begin
   fna := 'jim';
end;

function fnb(aFunc: TStringFunc): String;
begin
   if Assigned(aFunc) then
     fnb := aFunc
   else
     fnb := fna;
end;

end.

=== unit jim end ===

And your main program will then look like this:

=== main program begin ===

uses jim;

function fna: String;
begin
   fna := 'fred';
end;

begin
   writeln(fnb(@fna)); // will print "fred"
   writeln(fnb); // will print "jim"
end.

=== main program end ===

For further information about procedure/function variables I refer you 
to the documentation: 
http://www.freepascal.org/docs-html/ref/refse17.html#x45-520003.6

Of course you are free to ask further questions if you need help on this 
or another topic. ;)

Regards,
Sven



More information about the fpc-pascal mailing list