07-14-2017 01:45 AM
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.
Solved! Go to Solution.
07-14-2017 05:27 AM
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.
07-14-2017 05:53 AM
Thank you, Andreas!
The CLASS-solution is fine.