Written by

Developer at Matirx, Israel
Question Nael Nasereldeen · Jun 27, 2019

Detecting how many parameters were passed to a function

Hi,

We have a function that takes two parameters, the second one is for output value:

MyFunc(Param1,Param2)

 S Param2="it's all good"

Q 1

 

How can we detect if the caller called the function with one, or two arguments?

Meaning,  how to distinguish this call:

S Result=$$MyFunc(1)

from this call:

S Result=$$MyFunc(1,.OutVal)

 

Thanks!

Nael

Comments

Robert Cemper · Jun 27, 2019
MyFunc(Param1,Param2) Public {
    if $d(Param2)  write " 2 params",! 
    else  write " 1 param",!
  
    S Param2="it's all good"

   Q 1

}
0
Nael Nasereldeen  Jun 27, 2019 to Robert Cemper

Hi,

Thank you,

That would work if the caller is nice enough to set the second variable to null before calling the function. 

But he may not do it..

So if the function is:

MyFunc(Param1,Param2)
    if $d(Param2) {
    Answer= " 2 params"
    Else {
    Answer= " 1 params"
    }
  
    Param2="it's all good"
   Answer

Then:

USER>w $$MyFunc^%ZWBNAEL(1)
 1 params
USER>w $$MyFunc^%ZWBNAEL(1,.V)
 1 params

0
Nael Nasereldeen  Jun 27, 2019 to Alexander Koblov

Thank you Alexander,

I was not familiar with $stack , might be useful in various situations.

0
Nael Nasereldeen  Jun 27, 2019 to Vitaliy Serdtsev

Nice! 

I did not know this was possible. 

Thank you!

0
Robert Cemper  Jun 27, 2019 to Nael Nasereldeen

I miss   Public {   } in your example
it ensures that only parameters are visible as <Private variables>  or all %*
 

0
Alexander Koblov · Jun 27, 2019

Hi Nael

Not possible, as far as I know.

You can play with $stack. Something like this:

 set Result=$$MyFunc(1,.Out)
 quit
MyFunc(Param1,Param2)
 write $stack($stack-1,"MCODE"),!
 set Param2="it's all good"
 quit 1

USER>d ^test
 set Result=$$MyFunc(1,.Out)

But here you are looking at parsing plain strings, and this is error-prone.

0
Vitaliy Serdtsev · Jun 27, 2019
  w $$MyFunc(1),!,
    $$MyFunc(1,.V)," V=",V,!

MyFunc(p...)
  Answer=p_" params"
  s:p=2 p(2)="it's all good"
  Answer


USER>do ^test
1 params
2 params V=it's all good
0