Question
· Dec 13, 2019

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

 

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)

}

Discussion (3)2
Log in or sign up to continue

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