views:

402

answers:

3

The below example generates an error:

VBScript compilation error: Cannot use parentheses when calling a Sub

This error does not occur if all parameters are not objects.

Is there a special way to pass object parameters to VBScript functions?

Option Explicit

Dim obj

Function TestFunc(obj)
 WScript.Echo "Why doesn't this work?"
End Function

Set obj = CreateObject("Scripting.Dictionary")
obj.Add("key", "val")

TestFunc(obj) ' Error here!
A: 

This line

obj.Add("key", "val")

is causing the issue

change to

obj.Add "key", "val"

obj.Add is a sub which like the error says you can't use parens but your TestFunc is a function and can be called with parens

Gratzy
You can only use parenthesis when a function returns a value (or the sub/function only takes 1 parameter). Simply using the function keyword is not enough.
Tester101
+1  A: 

Only use parenthesis when you get a return value. Also use Sub instead of Function for functions that don't return something.

svinto
This worked. The function I'm using actually does return a value but I was not assigning it to anything. If I assign the return value or remove the parenthesis, it works. The behavior is quite odd but I'm not surprised given how long VBScript has been around. Thanks.
A: 

Parenthesis can only be used when..

  1. You are calling a function that returns a value.
  2. When the sub/function you are calling only takes 1 parameter.
  3. If you precede the call with the Call keyword eg. Call TestFunc(obj)
Tester101