How to generate variable parameters for calling method with variable input parameters?

Primary tabs

 

s txt(1)="1"

s txt(2) = "2"

s txt(3)="3"

...

s txt(n)="n"

 Instead of hardcoding "d ..write(txt1(1),txt(2),txt(3))"

Is it possible to write code to generate the input parameters to do d ..write(txt1)...txt(n))?

ClassMethod write(Arg... As %String)

{

  s cnt = $GET(Arg, 0)

}

  • + 1
  • 0
  • 130
  • 0
  • 3

Answers

set n=10
for i=1:1:n { write "set txt("_i_")="""_i_"""",!}

Would output

set txt(1)="1"
set txt(2)="2"
set txt(3)="3"
set txt(4)="4"
set txt(5)="5"
set txt(6)="6"
set txt(7)="7"
set txt(8)="8"
set txt(9)="9"
set txt(10)="10"

You can paste it where needed.

If you have an array you can:

set txt(1)="1
...
set txt(n)="n


ClassMethod write(txt As %ArrayOfDataTypes)
{
  set​ arg1=$get(txt(1))
  ...
  set arg2=$get(txt(n)

or

  set l="" for i=1:1 {
         set l=$order(txt(l))
         quit:l=""
         set arg(i)=txt(l)​​​​​​


}

and call it with the array ByRef:

do ..write(.txt)

 

 

 

 

 

 

I think the answers so far have missed the point. The number of arguments itself is variable. This is handy for things like building a complex SQL statement and set of arguments to pass to %SQL.Statement:%Execute, for example.

The data structure here is an integer-subscripted array with the top node set to the number of elements. (The top node is what's missing in the example above). Subscripts can be missing to leave the argument at that position undefined.

Here's a simple example:

Class DC.Demo.VarArgs
{

ClassMethod Driver()
{
    Do ..PrintN(1,2,3)
    
    Write !!
    For i=1:1:4 {
        Set arg($i(arg)) = i
    }
    Kill arg(3)
    ZWrite arg
    Write !
    Do ..PrintN(arg...)
}

ClassMethod PrintN(pArgs...)
{
    For i=1:1:$Get(pArgs) {
        Write $Get(pArgs(i),"<undefined>"),!
    }
}

}

Output is:

d ##class(DC.Demo.VarArgs).Driver()
1
2
3


arg=4
arg(1)=1
arg(2)=2
arg(4)=4

1
2
<undefined>
4