After performing an assignment in a function, to
indicate the value it returns, somewhere after the assignment and before
the End Function line, you can type the name of the function, followed by the =
sign, followed by the value the function returns. Here is an example in
which a function returns a name:
<script language="vbscript" type="text/vbsscript" runat="server">
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = "Gertrude"
LastName = "Monay"
GetFullName = LastName & ", " & FirstName
End Function
</script>
Alternatively, instead of using
the name of the function to indicate the value it returns, you can type Return,
followed by the value or the expression that the function returns. Based
on this, the above function could also be created as follows:
<script language="vbscript" type="text/vbsscript" runat="server">
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = "Gertrude"
LastName = "Monay"
Return LastName & ", " & FirstName
End Function
</script>
You can also use some local variables in the function
to perform an assignment and then assign their result to the name of the
function.
As done for the sub procedure, in order to use a function in your program,
you must call it. Like a sub procedure, to call a function, you can simply type
its name in the desired section of the program.
Since the primary purpose of a function is to return a value, to better
take advantage of such a value, you can assign the name of a function to a
variable in the section where you are calling the function.
Here is an example:
<%@ Page Language="VB" %>
<html>
<head>
<script language="vbscript" type="text/vbsscript" runat="server">
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = "Gertrude"
LastName = "Monay"
Return LastName & ", " & FirstName
End Function
</script>
<title>Exercise</title>
</head>
<body>
<%
Dim FullName$
FullName = GetFullName()
Response.Write(GetFullName$)
%>
</body>
</html>
Here is an example of running this program:
Depending on an author, in the Visual Basic language, the
word "procedure" includes either a sub-procedure created with the Sub
keyword, or a function created with the Function keyword. In the same
way, for the rest of our lessons, the word procedure will be used to represent
both types. Only when we want to be precise will we use the expression "a
sub-procedure" to explicitly mean the type of procedure that does not
return a value. When the word "function" is used in our lessons, it
explicitly refers to the type of procedure that returns a value.
|
Introduction to Functions
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment