Tuesday, April 5, 2011

Functions and Procedures (Subroutines)



Functions are an important part of programming as they allow you to create chunks of code that perform a specific task. VBScript has a number of built-in functions that are part of the language. VBScript also gives you the ability to create your own functions. Your VBScript programs may be made up of one function or several functions.


Built-in:


The built in functions are there to perform a number of actions that programmers expect to be part of a programming language. Some of the built in functions include:


 CLng(string value), CInt(string value), Cdate (value), etc.. We will use these functions later in the course.


Programmer Created:


Subroutines that you create start with the command “sub” and are followed by the name for the subroutine. For example:


Sub subroutine_name( argument1, argument2, … )
      .
      .
      VBScript statements go here
      .
      .
End Sub


Usually the name is an indicator of the action the function is going to provide such as “checkForm”. The name is followed by a set of parenthesis and inside the parenthesis there can be a number of arguments. Arguments are the variable names that will be used for values (data) being passed to the subroutine.


Two ways to invoke a Subroutine


There are two ways to invoke a subroutine, the later is the preferred method as it makes the code more readable: 


  1. use the subroutine name followed by the arguments.
      I.e. showAlertBox arg1
   2. use the call statement followed by the subroutine name with the
      arguments in brackets.
      I.e. Call showAlertBox( arg1)


Function … End Function


All functions have the ability to pass back a single value. Another way of saying this is you can pass data into a function using its arguments, and get the results out with a returned value. Functions can only return one value. In the example below the sum of two numbers is returned by the add_two_num() function. The trick to getting the function to return a value is to assign the value to a function name, see the second line in the first function below.

dim globalVar
globalVar = 1999
function add_two_num( a, b)
       add_two_num = a + b
end function
function mainProgram()
       dim x, y, total
       x = 5: y = 3: total = 0
       total = add_two_num( x , y )
       alert(total)
end function


In the above example:



  • The function main Program declares variables and assigns their initial values  as follows - “x” equal to 5, “y” equal to 3 and “total” equal to 0
  • Then it calls the add_two_num function and passes in the values of x and y.
  • In the add_two_num function the values are added together and stored in a variable named sum.
  • The value of sum is returned back to the main Program function and stored in the variable named total.
  • The value of total is then displayed to user in an alert box.

No comments:

Post a Comment