Solved

Function with n parameters

Posted on 2004-04-30
12
426 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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
 
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

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Delphi Form ownership 4 88
How to renew a Delphi rad-studio licence? 5 64
Delphi: making a BW image transparent 10 38
Twebbrowser in Fire monkey android scrolling to bottom 1 30
This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

770 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