One of the keys to successful programming is code reuse - rather than rewrite useful functions and subroutine, programmers store them in libraries and then use these libraries in any new applications that they may create. The only problem for VBScript developers is the fact that VBScript does not have a native method for loading libraries (such as C++'s include). However, that's not really a problem since it doesn't actually need its own method.
As any VBScript programmer develops applications they will write functions and subroutines - many of which will be useful in more than one application. Take, for example, the VB commands dir and mkdir - these are very useful in any application but do not exist in VBScript. The obvious thing for the VBScript programmer to do is to create these commands themselves and then use them where required.
Therefore, they will need to:
- create a function to replicate the dir functionality and store it in a vbs file
- create a subroutine to replicate the mkdir functionality and store it in the same vbs file
- create a second vbs file and load the library vbs file
- use the functionality from library in the new application
Creating a VBScript Library
The VBScript library is just like any other vbs file - a text file containing VBScript functions and subroutines. The only difference is that it contains no code to run the functions and subroutines - that will be in the applications that use the library.
The first method to add to the library is a function that can check for the existence of a directory - this actually just encapsulates the FSO's (File System Object) folderexists method. It's worth noting at this point that variables can be defined and initiated on the same line by use the colon:
This is a function because it returns true or false depending whether the designated folder exist or not, however the next piece of code is a subroutine - it doesn't return any result, it just creates a new directory:
Here the subroutine works its way from the top directory creating any folder as required.
The next stage, of course, is to make uses of the library in an VBScript application.
Using the VBScript Library
The VBScript library is stored in one file (for exampleH:\vbscript\filesystem.vbs) and the application is stored in another (for exampleC:\vbscript\use_filesystem.vbs). VBScript does not have an include statement, instead the library is loaded by making use of the FSO (the File System Object):
The next stage is to read the library file (in read-only mode) and then execute the text in the file:
And then the functionality loaded from the library can be used in this application:
In this example the application will:
- initially return false (because the folder doesn't exist yet)
- create the folder
- return true (because the folder now exists)
Of course, the programmer can reuse the functionality in any other applications that they write.