Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

vbscript - How to call a function (with parameters) which is in function library, taking the function name from a variable?

I'm trying to use getref to call a function from the function library associated with the test. My code -

In action1

str = "sample"
msg = "hi"
x = GetRef("Function_"&str)(msg)
msgbox x

In the function Library,

Function Function_sample(strMsg)
    Function_sample = strMsg
End Function

I'm getting the error -

"Invalid procedure call or argument."

But it works fine if the function is placed in the same action. How to call a function (with parameters) which is in function library, taking the function name from a variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Minimalistic working example:

Lib.vbs:

Option Explicit

Function Twice(n)
  Twice = n + n
End Function

Main.vbs:

Option Explicit

Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")

ExecuteGlobal goFS.OpenTextFile(".lib.vbs").ReadAll()

Dim fpTwice : Set fpTwice = GetRef("Twice")

WScript.Echo fpTwice(42)

Output:

cscript main.vbs
84

The error message "... runtime error: Invalid procedure call or argument: 'GetRef'" indicates that the (importing of the) function library is to blame.

Update:

I think that it is plausible to assume that the VBScript engine keeps a table associating sub/function/method names with callable code to be able to do literal/direct calls:

n = Twice(11)

and that GetRef("Twice") accesses this table. So I would never expect an indirect/'function pointer' call or a GetRef() to fail when the literal invocation succeeds.

But according to this and that, there are at least four ways to 'import' libraries/modules into QTP, and as I don't use QTP I can't rule out, that some (or even all) of these methods do something silly to cause the mis-behaviour you describe.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...