Search code examples
functionsyntaxreturnternary-operatorautoit

Meaning of ":" and "?"


I found semicolons & question marks in a Return statement of an AutoIt script:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6

Func A()
  ;do somethingA
EndFunc

Func B($a,$b,$c)
  ;do somethingB
EndFunc

Func C($a,$b,$c,$d)
  ;do somethingC
EndFunc

Func CallFunc( $f, $a = Default, $b = Default, $c = Default, $c = Default )
  Return FuncName($f) = "A" ? $f() : FuncName($f) = "B" ? $f($a,$b,$c) : $f($a,$b,$c,$d)
EndFunc

Example()

Func Example()
  CallFunc( A )
  CallFunc( B, 1, 2, 3 )
  CallFunc( C, 1, 2, 3, 4 )
EndFunc

I know FuncName() returns the name of a function stored in a variable, but I don't know what question-marks & semicolons mean in this Return statement:

Return FuncName($f) = "A" ? $f() : FuncName($f) = "B" ? $f($a,$b,$c) : $f($a,$b,$c,$d)

Solution

  • I don't know question-marks & semicolons meanings

    As per Documentation - Keywords - Ternary operator:

    Conditionally chooses one of two responses based on the result of an expression.

    For example;

    Return $g_bBlockInput ? $MOE_BLOCKDEFPROC : $MOE_RUNDEFPROC
    

    is functionally equivalent to:

    If $g_bBlockInput Then
    
        Return $MOE_BLOCKDEFPROC
    
    Else
    
        Return $MOE_RUNDEFPROC
    
    EndIf
    

    So

    Return FuncName($f) = "A" ? $f() : FuncName($f) = "B" ? $f($a,$b,$c) : $f($a,$b,$c,$d)
    

    equals:

    If FuncName($f) = "A" Then
    
        Return $f()
    
    Else
    
        If FuncName($f) = "B" Then
    
            Return $f($a,$b,$c)
    
        Else
    
            Return $f($a,$b,$c,$d)
    
        EndIf
    
    EndIf
    

    Whatever that code's purpose seems a case for Switch...Case...EndSwitch instead. Popular use of ternary operator includes conditional assignment. Example:

    Global Const $g_bState = True
    Global Const $g_sState = $g_bState ? 'ON' : 'OFF'
    
    ConsoleWrite('$g_bState = ' & $g_sState & @CRLF)