VBScript conditional short-circuiting workaround

后端 未结 9 2092
心在旅途
心在旅途 2021-02-19 05:15

I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won\'t let you

相关标签:
9条回答
  • 2021-02-19 05:27

    If you write it as two inline IF statements, you can achieve short-circuiting:

    if not isNull(Rs("myField")) then if Rs("myField") <> 0 then ...
    

    But your then action must appear on the same line as well. If you need multiple statements after then, you can separate them with : or move your code to a subroutine that you can call. For example:

    if not isNull(Rs("myField")) then if Rs("myField") <> 0 then x = 1 : y = 2
    

    Or

    if not isNull(Rs("myField")) then if Rs("myField") <> 0 then DoSomething(Rs("myField"))
    
    0 讨论(0)
  • 2021-02-19 05:28

    Nested IFs (only slightly less verbose):

    if not isNull(Rs("myField")) Then
       if Rs("myField") <> 0 then
    
    0 讨论(0)
  • 2021-02-19 05:28

    Would that there were, my friend -- TernaryOp is your only hope.

    0 讨论(0)
  • 2021-02-19 05:29

    Yeah it's not the best solution but what we use is something like this

    function ReplaceNull(s)
        if IsNull(s) or s = "" then
            ReplaceNull = "&nbsp;"
        else
            ReplaceNull = s
        end if
    end function
    
    0 讨论(0)
  • 2021-02-19 05:32

    Two options come to mind:

    1) use len() or lenb() to discover if there is any data in the variable:

    if not lenb(rs("myField"))=0 then...
    

    2) use a function that returns a boolean:

    if not isNothing(rs("myField")) then...
    

    where isNothing() is a function like so:

    function isNothing(vInput)
        isNothing = false : vInput = trim(vInput)
        if vartype(vInput)=0 or isEmpty(vInput) or isNull(vInput) or lenb(vInput)=0 then isNothing = true : end if 
    end function
    
    0 讨论(0)
  • 2021-02-19 05:39

    I always used Select Case statements to short circuit logic in VB. Something like..

    Select Case True
    
    Case isNull(Rs("myField"))
    
        myField = 0
    
    Case (Rs("myField") <> 0)
    
        myField = Rs("myField")
    
    Case Else
    
        myField = -1        
    
    End Select
    

    My syntax may be off, been a while. If the first case pops, everything else is ignored.

    0 讨论(0)
提交回复
热议问题