Lesson 11: VBScript functions|
Lesson 11: VBScript functions
Learn how to use VBScript functions in your ASP pages.
In lesson 6 you learned about subroutines.
A subroutine is a batch of VBScript code that
is executed every time you call it.
The difference between a function and a sub is that
a sub will do some stuff (like printing something to the screen)
and then quit, while a function runs some code and then returns the
Result = 2 + 2
WhatIs2Plus2 = Result
As you can see we do two things with the line
first we call the function WhatIs2Plus2.
Then the function runs some code and sets a variable with the same name
as the function equal to the result. The function has now finished and
we are back where we called it. The value we got from the function is now
stored in WhatIs2Plus2 and we now write that value
out with: <%=WhatIs2Plus2%>. In this example
the result will always be 4, but what if we could tell the function what numbers to add?
To do this we need to use something called arguments.
It is variables that you send to the function when you call it, and
the function can use those values in its code. Here is the function above modified with
FUNCTION WhatIs(Number1, Number2)
Result = Number1 + Number2
WhatIs = Result
X = 3
Y = 4
The result of the function will now depend on the values of
X and Y.
You can think of functions like small machines.
If you feed them with something in one end (e.g. a number),
something pops out in the other end (e.g. an error message).
SELECT CASE number
Write_Error = "Field number one is empty, please fill it out!"
Write_Error = "The email address you wrote is not valid!"
Write_Error = "Error updating SQL database!"
Write_Error = "Field number two is empty, please fill it out!"
Write_Error = "Unspecified error!"
This script will write an error message based on the
numeric value of x (1,2,3,4 or 5).
To see how this script works, view the demo.
To get the most of your functions, you can save them
in separate files, and include them in any scripts
that needs them. This makes things easy to update too.
Example: Circle function
SELECT CASE problem
Result = 2 * 3.14 * radius
Result = 3.14 * Sqr(radius)
Circle = Result
In this example the function calculates
the circuit or the area of a circle based on
the parameters. The y parameter is the radius of
the circle, and MyString should be circuit if you
want to calculate the circuit of the circle, and
area if you want to find the area of the circle.
Try the demo to see how it works.
Now you have seen the power of functions, and
you should use functions if you use the same
group of statements more than one time in a script.
Where to go next:
Take a look at our lessons page
to get an overview of all our lessons.