Wednesday, August 10, 2005

The Mexican IF in VBScript

The trouble with an IIF, at least in VBScript, is that both the true and the false get evaluated on invocation:
Function IIF( theCond, theTrue, theFalse )
        Dim theResult
        If theCond Then
                theResult = theTrue
                theResult = theFalse
        End If
        IIF = theResult
End Function
So I tried delaying evaluation:
Function EIF( theValue, theTest, theTrue, theFalse )
        Dim theResult
        Dim theBool
        theTest = Replace( theTest, "$1", "theValue" )
        theTrue = Replace( theTrue, "$1", "theValue" )
        theFalse = Replace( theFalse, "$1", "theValue"
        theBool = Eval( theTest )
        If theBool = True Then
                theResult = Eval( theTrue )
                theResult = Eval( theFalse )
        End If
        EIF = theResult
End Function
Calling it was to work like this,
        i = 1
        j = EIF(i,"$1=1","$1", "$1*$1")
That is, if i = 1 then j = i else j = i * i. If I'd just used IIF it would have been
        i = 1
        j = IIF(i=1,i,i*i)
and the true and false parts would have been evaluated before invocation of the IIF function.
I gave up in the end, but it was fun ... sort of.


Anonymous said...

What's wrong with

Function IIF(c, t, f)
Dim ret
If c Then
ret = Eval(t)
ret = Eval(f)
IIF = ret
End Function

j = IIF(i=1, "i", "i*i")

That seems to be what you're looking for — the lazy evaluation of t and f, not lazy evaluation of c!

Bruce M. Axtens said...


This is part of the reason I got this blog off the ground ... I need the odd reality check which your comment graciously provides. Thanks!