VBScript Functions
When you are programming in VBScript and other languages you may find that you have to program the same code over, and over, and over. This is usually a sign that you should be using a function to reduce this code repetition. Besides that, functions are also useful to increase code readability (when done right).VBScript Function Creation
Let's start off with a really simple example to show the syntax for creating a function. The function myAdd will take two numbers and print out the result.VBScript Code:
<script type="text/vbscript">
Function myAdd(x,y)
myAdd = x + y
End Function
'Let's use our function!
Dim result
result = myAdd(10,14)
document.write(result)
</script>
Display:
24
This may not look that complex, but there is actually quite a lot going on this simple example.
We first created our function myAdd, which takes two arguments x and y.
These two arguments are added together and stored into the myAdd variable.When our VBScript code executes it first stores the function for later use, then reaches result = myAdd(10,14). VBScript then jumps to the function myAdd with the values x = 10 and y = 14.
Notice that the variable that we store our result in is the same as the function name myAdd. This is on purpose. In VBScript you can only return a value from a function if you store it inside a variable that has the same name as the function.
After the function has completed executing its code the line result = myAdd(10,14) is now result = 24 where result is set equal to the the result of the myAdd function. We then print out the value of result which is 24.
We recommend that you play around with creating VBScript functions for a while to get a better feel for this important programming technique.
0 comments:
Post a Comment