Solved

Function with n parameters

Posted on 2004-04-30
12
423 Views
Last Modified: 2010-04-05
I need to implement a function with variable parameters.
Something like writeln from pascal.
Example:  writeln('TESTE',2,'TESTE',1) that returns to me a string 'TESTE 2 TESTE 1', but I can have n parameters.
How Can I do that with delphi?

Thanks.
0
Comment
Question by:MauricioMaia
  • 4
  • 2
  • 2
  • +4
12 Comments
 
LVL 11

Expert Comment

by:shaneholmes
ID: 10963714
OTTOMH, something like this:

function MyWriteln (var Lines: TStrings);
begin
 result:= '';
 for I:= 0 to Lines.Count - 2 do
  result:= result + Lines[I] + ' ';
 result:= result + Lines[I];
end;


Then you just add what you want to Lines

example

MyLines.Add('One');
MyLines.Add('Two');

MyWriteln(MyLines);


Shane
0
 
LVL 26

Accepted Solution

by:
Russell Libby earned 50 total points
ID: 10963792
If all the parameters are the same, then declare the function as

function x(params: Array of type): result;

where x is the function name
type is the data type
and result is the desired data type

eg:

// example
function writeln(Params: Array of String): String;
var  index:      Integer;
begin

  result:='';
  for index:=0 to High(Params) do
  begin
     result:=result+Params[index]+#32;
  end;

end;
called like

writeln(['one', 'two', 'three']);

Now, if the data types can vary, then use array of const, for example:

procedure WriteData(Values: Array of Const);
var  count:      Integer;
     dwWrite:    DWORD;
     buffer:     Array [0..4095] of Char;
begin

     // Write out the const values
     for count:=0 to High(Values) do
     begin
        // Set buffer to null terminated
        buffer[0]:=#0;
        with Values[count] do
        begin
           // Handle the data type
           case VType of
              vtInteger   :  Str(VInteger, buffer);
              vtBoolean   :  Str(Integer(VBoolean), buffer);
              vtChar      :
              begin
                 buffer[0]:=VChar;
                 buffer[1]:=#0;
              end;
              vtExtended  :  Str(VExtended^:0:2, buffer);
              vtString    :  lstrcpy(@buffer, PChar(String(VString^)));
              vtPChar     :  lstrcpy(@buffer, VPChar);
              vtObject    :  lstrcpy(@buffer, PChar(String(VObject.ClassName)));
              vtClass     :  lstrcpy(@buffer, PChar(String(VClass.ClassName)));
              vtAnsiString:  lstrcpy(@buffer, PChar(String(VAnsiString)));
              vtCurrency  :  Str(VCurrency^:0:2, buffer);
              vtInt64     :  Str(VInt64^, buffer);
           end;
           // Write the buffer to the console
           WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), @buffer, lstrlen(@buffer), dwWrite, nil);
        end;
     end;
end;

which can be called like

  WriteData(['test1', 'test2', 10, 100.3]);


Hope this helps,
Russell




0
 
LVL 26

Expert Comment

by:Russell Libby
ID: 10963840
Or, put into the context of the original question:

function MyWriteln (Values: Array of Const): String;
var  dwCount:    DWORD;
     dwWrite:    DWORD;
     szValue:    String;
     lpPos:      PChar;
begin

  // Set default result
  result:='';

  // Write out the const values
  for dwCount:=0 to High(Values) do
  begin
     // Set string value
     szValue:='';
     // Convert value to string
     with Values[dwCount] do
     begin
        // Handle the data type
        case VType of
           vtInteger   :  Str(VInteger, szValue);
           vtBoolean   :  Str(Integer(VBoolean), szValue);
           vtChar      :  szValue:=VChar;
           vtExtended  :  Str(VExtended^:0:2, szValue);
           vtString    :  szValue:=PChar(String(VString^));
           vtPChar     :  szValue:=VPChar;
           vtObject    :  szValue:=String(VObject.ClassName);
           vtClass     :  szValue:=String(VClass.ClassName);
           vtAnsiString:  szValue:=PChar(String(VAnsiString));
           vtCurrency  :  Str(VCurrency^:0:2, szValue);
           vtInt64     :  Str(VInt64^, szValue);
        else
           szValue:='';
        end;
        // Write the string to the result
        if (dwCount = High(Values)) then
           result:=result+szValue
        else
           result:=result+szValue+#32;
     end;
  end;

end;


Regards,
Russell
0
 
LVL 7

Expert Comment

by:sftweng
ID: 10963980
It's dangerous to use a variable number of parameters unless you use something like a SET as one of the parameters.

Pascal did not allow it. Programmers make mistakes if they don't know how many parameters to code. Or maybe thay use the wrong parameters.

Strong typing, with no freedom to do things like change the number of parameters, forces you to think very carefully about your design. That's what you should be doing, not just programming.
0
 
LVL 26

Expert Comment

by:Russell Libby
ID: 10964028

Format, WriteLn, AddRecord, AppendRecord, etc... I could go on for awhile. These all make use of "array of const".

In regards to typing, these ARE strongly typed, albeit as a record structure in the form of TVarRec. This is a strongly typed structure, and in short, I don't see the issue with the code posted above.

Russell


0
 
LVL 7

Expert Comment

by:sftweng
ID: 10964088
Russell, no issue with passing an array, just with having a variable number of parameters.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 12

Expert Comment

by:Lee_Nover
ID: 10966814
I would suggest the same as rllibby - use array of const
but I also agree with sftweng about code design
0
 
LVL 12

Expert Comment

by:Ivanov_G
ID: 10967154

   function DoSomething (Params : Variant) : Integer;
   var
     i : Integer;
     Param : Variant;
   begin
     for i := VarArrayLowBound(Params, 1) to VarArrayHighBound(Params, 1) do
        begin
           Param := Params[i];
           // process the param
        end;
   end;


   when you want to call your function you build your Params like this :

   Params := VarArrayOf([A, 3, B, 'sdfgdfh']); // with different parameter count and types

0
 

Author Comment

by:MauricioMaia
ID: 10968513
Thanks guys,

But theres is a way to do this without using arrays?
Just like in C
where I can declare something like that
int sum(int numbers,...)
and then I use va_start, va_arg and va_end to get the values.
Thanks.





0
 
LVL 26

Expert Comment

by:Russell Libby
ID: 10968731
Yes, and it is through the array of const (which is called an open array). Using the code I provided above for the function MyWriteln (Values: Array of Const): String;

it is easily called like:

stringvar:=MyWriteLn(['TESTE', 1, 'TESTE', 2]);
stringvar:=MyWriteLn(['TESTE', 100.3, 5, True]);
stringvar:=MyWriteLn([1, 2, 3, 4,5 , 6, 7]);

And handles the following data types: Integer, Boolean, Char, Extended, String, PChar, Object, Class, AnsiString, Currency, and Int64. (all the mappings for TVarRec)

Regards,
Russell




0
 
LVL 14

Expert Comment

by:DragonSlayer
ID: 10973401
OffTopic:

Russell, WriteLn doesn't use Array of Const... it's written in assembly, and it checks the stack for parameters...
0
 

Author Comment

by:MauricioMaia
ID: 10995711
I will give points to rllibby. The array of const solve my problem.
But I was interested on a implementation like the old turbo pascal (just like DragonSlayer said), but I think that is not possible with delphi.
Thanks.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
In my programming career I have only very rarely run into situations where operator overloading would be of any use in my work.  Normally those situations involved math with either overly large numbers (hundreds of thousands of digits or accuracy re…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now