Understanding Procedures in VBScript - Final Concepts
(Page 5 of 5 )
The last concept that you need to be aware of is the proper use of parentheses when calling Subs and Functions. The rules are pretty simple: if you are calling a Sub, you do not enclose parameters in parentheses. If you are calling a Function, you do not enclose parameters in parentheses unless you are capturing its return value.
PrintMessageSub "This uses my Sub."
PrintMessageFunction "This uses my Function."
return = PrintMessageFunction("This also uses my function.")
Sub PrintMessageSub(strMessage)
WScript.Echo strMessage
End Sub
Function PrintMessageFunction(strMessage)
WScript.Echo strMessage
PrintMessageFunction = True
End Function
There is one exception to these rules. You must always use parenthesis any time you are using the Call statement.
Call PrintMessageSub("This uses my Sub.")
Call PrintMessageFunction("This uses my Function.")
return = PrintMessageFunction("This also uses my function.")
Sub PrintMessageSub(strMessage)
WScript.Echo strMessage
End Sub
Function PrintMessageFunction(strMessage)
WScript.Echo strMessage
PrintMessageFunction = True
End Function
The Call statement discards any return value; therefore, you cannot use the Call statement any time that you wish to capture a return value.
Learning to make proper use of procedures (along with parameters and scope) will take your scripting abilities to the next level. It is also important to keep these concepts in mind because they can have a dramatic effect on your script performance as well as the system resources required to run your script. The best way to learn about procedures is to look at code written by other, more advanced programmers. Pay attention to how and why they’ve used procedures.
As you progress, I do have a tip for you concerning procedures:
VBScript is executed linearly (meaning line-by-line) so avoid using procedures excessively. This will only make your code harder to follow. You should only use procedures when absolutely needed or when they can be used to simplify your existing code. Procedures should only be used in moderation.
So sit down and write some code, or go back through some code you’ve already written and look for ways that you can implement procedures to simplify your code. Until next time, keep coding!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |