开发者

how to treat empty parameters in function calls?

When you call a function like x = myfunc(a,b,,d) what happens with the 3rd parameter? is it empty? null? nothing?

I'm having issues with my function, say,

function myfunc(p1, p2, p3, p4)  
  if p3 <> "" then whatever  
end function

gives me a dreaded type mismatch

P.S. I'm trying to replace a COM object with vbscri开发者_如何学Pythonpt functions, and those empty parameter calls were done to the COM objects which didn't have a problem with those, but vbscript doesn't like them. I can't change the calls, only the functions so I need to treat the empty parameter somehow, just don't know how (tried isnull with no luck, also isempty no luck, and is nothing gives me an object required error)


The data type of missed parameters is ERROR.
I wrote an example, try the following:

Function IsMissing(p)
    IsMissing = (VarType(p) = vbError)
End Function

Function Myfunc(p1, p2, p3, p4)
    If IsMissing(p1) Then Response.Write "p1 is missing "
    If IsMissing(p2) Then Response.Write "p2 is missing "
    If IsMissing(p3) Then Response.Write "p3 is missing "
    If IsMissing(p4) Then Response.Write "p4 is missing "
End Function

str = myfunc(, , , 1)
'str = myfunc(1, 2, , ) 'causes error

Notice: The last parameter of function / sub cannot be blank because of syntax error.


In the spirit of teaching a man to fish:

The TypeName function will reveal to you what type it is.

MsgBox TypeName(p3) ' Returns string: "Error"

Instead of if p3 <> "" you can test for omitted arguments like this:

    If TypeName(p3) = "Error" Then MsgBox "Whatever!"

or, preferably,

    If VarType(p) = vbError Then MsgBox "Whatever!"
    ' vbError is a built-in constant whose value is 10.

But really, for best practice, your program design should avoid omitting arguments. VBScript isn't really made to deal with "optional" arguments.


VBScript doesn't support optional parameters. They can be simulated by passing an array or null values in, which isn't helpful in your situation since you can not change the calls. The next solution might be to consider changing the platform (may I suggest .Net) or an On Error Resume Next hack like the one below.

'Assuming a String Parameter
Dim strOptionalParameter As String
strOptionalParameter = p3

'We set the value of the optional parameter to a variable
'in case it blows up and moves on to this next statement.
If strOptionalParameter <> "" Then
'Rest of Code Here
End If
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜