Jump to content
Ian Branch

Function embedded in a function?

Recommended Posts

Hi Team,

I think, from time to time I have seen a function embedded in another function.  I think.

Something like..

function foobar(param1, param2: string): string;

var

somevar: string;

begin

  function inside(Param3: string): string;

  var  anothervar: string;

  Begin  

    Do something with Param3;

    ....

    ...

    Result := anothervar;

  end;

...

Somevar := inside(somestring);

Result := Somevar;

end;

Is this doable?  If so, what is the mechanism for it pls?

Why do I want to do this?  So I can embed a function in the main function and not have to have it as a separate app function.

 

Regards & TIA,

Ian

 

 

Share this post


Link to post

Yes, it is doable, but the syntax is slightly different than you showed. The inner function has to be defined before the 'begin' of the outer function, eg:

function foobar(param1, param2: string): string;
var
  somevar: string;

  function inside(Param3: string): string;
  var
    anothervar: string;
  Begin
    Do something with Param3;
    ...
    Result := anothervar;
  end;

begin
  Somevar := inside(somestring);
  Result := Somevar;
end;

This is covered in Embarcadero's documentation: Nested Routines

Edited by Remy Lebeau
  • Thanks 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×