2

For example, if I have a function in VBscript:

Function sum(a, b, c) sum = a + b + c End function 

Now, in the main, I make two variables and pass them into the function sum as the following:

Dim a : a = 1 Dim b : b = 2 Call sum(a, b) 

Will this work or not, and why? Thanks.

    4 Answers 4

    7

    It will not work, VBScript doesn't support optional arguments.
    I'd use a function that takes an array of numbers instead vary number of arguments to getting sum.

    Function sum(nums) Dim i, out For i = 0 To UBound(nums) out = out + nums(i) Next sum = out End function Call sum(Array(1, 2, 3, 4)) 
      6

      According to this, VBscript does not support optional arguments. You can do what they suggest and pass null values to your function.

      1
      • I prefer passing Empty instead of null, as this the most "Nothing" thing ^^CommentedNov 10, 2024 at 0:38
      3

      I hope this might help. I use dictionary object to pass variables to function so I can add new arguments without the need for refactoring existing code.

      dim params set params = CreateObject("Scripting.Dictionary") '...when I want to call a function params.add "variable_name", value: params.add "variable_name_2", value ': ... call fn_function_name(params) '...declaring a function function fn_function_name(byRef params_in) 'here I usually make sure that variable is of correct type, or that is set params_in("variable_name") = fn_check(params_in("variable_name"), "number") ' fn_check is a separate function ' ... function code goes here ... ' in order to user external dictionary "params" multiple times, I empty dictionary before exiting the function. This is possible because I set it as a reference (byRef) instead of value params_in.removeAll() end function 
      2
      • Even if you pass a copy of an object (i.e. a reference to data), changes applied to the copy will affect the original. So you last comment is misleading.CommentedNov 5, 2017 at 11:52
      • If you don't want the original params_in to be affected, use it byVal, and not byRef. Please also note that using the CreateObject("Scripting.Dictionary") Object is notably slow. Prefer using several input parameters in your function, then sometimes pass it Emptyvalues.CommentedNov 10, 2024 at 0:39
      2

      VBScript doesn't support optional arguments or method overloading. You can pass in null values to your function call, however.

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.