MsgBox “” vs MsgBox() in VBScript

前端 未结 5 738
旧巷少年郎
旧巷少年郎 2020-12-09 15:32

I\'m trying to write a VBScript and I\'m using functions such as Randomize, and MsgBox. I\'m curious as to what is the difference of using () and not using them. For example

5条回答
  •  余生分开走
    2020-12-09 16:10

    A callable piece of code (routine) can be a Sub (called for a side effect/what it does) or a Function (called for its return value) or a mixture of both. As the docs for MsgBox

    Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

    MsgBox(prompt[, buttons][, title][, helpfile, context])

    indicate, this routine is of the third kind.

    The syntactical rules of VBScript are simple:

    Use parameter list () when calling a (routine as a) Function

    If you want to display a message to the user and need to know the user's reponse:

    Dim MyVar
    MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
       ' MyVar contains either 1 or 2, depending on which button is clicked.
    

    Don't use parameter list () when calling a (routine as a) Sub

    If you want to display a message to the user and are not interested in the response:

    MsgBox "Hello World!", 65, "MsgBox Example"
    

    This beautiful simplicity is messed up by:

    The design flaw of using () for parameter lists and to force call-by-value semantics

    >> Sub S(n) : n = n + 1 : End Sub
    >> n = 1
    >> S n
    >> WScript.Echo n
    >> S (n)
    >> WScript.Echo n
    >>
    2
    2
    

    S (n) does not mean "call S with n", but "call S with a copy of n's value". Programmers seeing that

    >> s = "value"
    >> MsgBox(s)
    

    'works' are in for a suprise when they try:

    >> MsgBox(s, 65, "MsgBox Example")
    >>
    Error Number:       1044
    Error Description:  Cannot use parentheses when calling a Sub
    

    The compiler's leniency with regard to empty () in a Sub call. The 'pure' Sub Randomize (called for the side effect of setting the random seed) can be called by

    Randomize()
    

    although the () can neither mean "give me your return value) nor "pass something by value". A bit more strictness here would force prgrammers to be aware of the difference in

    Randomize n
    

    and

    Randomize (n)
    

    The Call statement that allows parameter list () in Sub calls:

    s = "value" Call MsgBox(s, 65, "MsgBox Example")

    which further encourage programmers to use () without thinking.

    (Based on What do you mean "cannot use parentheses?")

提交回复
热议问题