DIAdem

cancel
Showing results for 
Search instead for 
Did you mean: 

FUNCTION Procedure with optional inputs

Solved!
Go to solution

Hello guys,

I'm looking for a way to create a function (UDF) with optional parameters, which can be set, but are not mandatory.

Just a simple example:

Function mean(a, b, c, {way})
'
Select Case way
 Case "geo"
  mean = SQR(a^2 + b^2 + c^2)
 Case ""
  mean = (a + b + c)/3
End Select
'
End Function

Here the function has the additional parameter, which is optional.

 

 

Is there any way to get this in Diadem?
Our current version is 2015.

0 Kudos
Message 1 of 3
(3,458 Views)
Solution
Accepted by topic author Dia791

There are no optional parameters in vbscript.
Either you need to handle null or there is a way to use an Array.

 

Option Explicit

function mean(byRef v)

  dim way : way = ""
  
  Select Case UBound(v)
    case 2
      ' nothing to do
    case 3
      way = v(3)
    case else
      err.Raise 100, "", "unsupported number of arguments"
  end select
  
  dim a : a = v(0)
  dim b : b = v(1)
  dim c : c = v(2)
  
  Select Case way
    Case "geo"
      mean = SQR(a^2 + b^2 + c^2)
    Case ""
      mean = (a + b + c)/3
  End Select
end function

MsgBox mean(Array(1,2,3)) & VBCRLF & mean(Array(1,2,3, "geo"))

Potentially it is better to use multiple methods or a class

 

MsgBox new CMean.Calc(1,2,3) & VBCRLF & new CMean.Init("geo").calc(1,2,3)


class CMean
  function Init(byVal mode)
    set Init = me
    way = mode
  end function
  
  function Calc(byVal a, byVal b, byVal c)
    Select Case way
      Case "geo"
        Calc = SQR(a^2 + b^2 + c^2)
      Case ""
        Calc = (a + b + c)/3
    End Select
  end function
  
  Private Sub Class_Initialize()
    way = ""
  End Sub

  private way
end class

The advantage of the class Instance is that you can store it and have different implementations with the same interface.

 

 

0 Kudos
Message 2 of 3
(3,428 Views)

Thank you, Andreas!
The CLASS-solution is fine.

0 Kudos
Message 3 of 3
(3,425 Views)