I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago.
I have an array of imagefile paths, like so:
dim banners, arrKeys, i
set banners=CreateObject("Scripting.Dictionary")
banners.Add "banner1.jpg", "http://www.somelink.com"
banners.Add "banner2.jpg", "http://www.somelink.com"
banners.Add "banner3.jpg", "http://www.somelink.com"
This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages).
If Not banners Is Nothing then
' then loop through the Dictionary and make a list of image links
End if
The problem is that if banners
is not instantiated on the page (it's not on all pages), I get a Can't find object
error
What's the proper way to check if an object exists in VB Script?
IsObject
could work, butIsEmpty
might be a better option - it is specifically intended to check if a variable exists or has been initialised.To summarize:
IsEmpty(var)
will test if a variable exists (without Object Explicit), or is initialisedIsNull(var)
will test if a variable has been assigned toNull
var Is Nothing
will test if a variable has beenSet
toNothing
, but will throw an error if you try it on something that isn't an objectIsObject(var)
will test if a variable is an object (and will apparently still returnFalse
ifvar
isEmpty
).If a variable is declared, but not initialized, its value will be
Empty
, which you can check for with theIsEmpty()
function:banners
will only be equal toNothing
if you explicitly assign it that value withSet banners = Nothing
.You will have problems, though, with this technique if you have
Option Explicit
turned on (which is the recommendation, but isn't always the case). In that case, ifbanners
hasn't beenDim
ed and you try to testIsEmpty(banners)
, you will get a runtime error. If you don't haveOption Explicit
on, you shouldn't have any problems.edit: I just saw this related question and answer which might help, too.
You need to have at least
dim banners
on every page.Don't you have a
head.asp
or something included on every page?Somewhat related is
IsMissing()
to test if an optional parameter was passed, in this case an object, like this:@Atømix: Replace
and use
Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.
@Cheran S: I tested my snippets above with
Option Explicit
on/off and didn't encounter errors for either version, regardless of whetherDim banners
was there or not. :-)Neither of IsEmpty, Is Object, IsNull work with the "Option Explicit" Setting, as stealthyninja above has misleadingly answered. The single way i know is to 'hack' the 'Option Explicit' with the 'On Error Resume Next' setting, as Tristan Havelick nicely does it here: Is there any way to check to see if a VBScript function is defined?