Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - Calling procedure with optional VAR parameters?

Delphi 2010 - I have a routine which takes a string and processes it. There are 3 different types of processing, and I may need any combination, including all 3 ways of processing. I am trying to determine how to call my routine, but everything I try is causing issues. What I want to do is call the procedure something like this...

StringProcess(StartString1, VarProcess1, VarProcess2, VarProcess3);

but it could just as easily be this is I only want 2 of the processes

StringProcess(StartString1, '', VarProcess2, VarProcess3);

The procedure definition is something like

procedure StringProcess(StartString: string; var S1:String; var S2:string; var S3:string);

So in summary... How do I define my procedure to return between 1 and 3 VAR variables? Delphi is wanting me to always pass 3 variables, and I just have to ignore the one if I don't need it. Is there a way to pass "non-existant" VAR parameters, and just ignore them as needed?

Thanks

like image 636
user1009073 Avatar asked Dec 01 '22 19:12

user1009073


1 Answers

A var parameter cannot be optional, it must be passed a variable. For what you are looking for, use pointers instead:

procedure StringProcess(StartString: string; S1:PString; S2:Pstring; S3:Pstring);
begin
  ...
  if S1 <> nil then
  begin
    // Use S1^ as needed...
  end;
  ...
end;

Then you can do things like this:

StringProcess(StartString1, @VarProcess1, @VarProcess2, @VarProcess3);
StringProcess(StartString1, nil, @VarProcess2, @VarProcess3);
StringProcess(StartString1, nil, nil, @VarProcess3);
StringProcess(StartString1, @VarProcess1, nil, @VarProcess3);
...
like image 65
Remy Lebeau Avatar answered Dec 10 '22 21:12

Remy Lebeau