How to Determine If a Variable Exists in Memory

ID: Q115990

The information in this article applies to:

SUMMARY

If a nonexistent variable is called in FoxPro, a "Variable <variable name> not found" error message will result. This article explains how you can determine whether a particular variable exists in memory.

MORE INFORMATION

There are two ways you can determine the existence of a variable.

Method 1

The TYPE() function will return a "U" if the variable does not exist in memory. The following sample code illustrates this behavior.

   *** Begin Example Code ***

   m.var1='m.var1 does exist'         && Initialize a variable.
   WAIT WINDOW TYPE('m.var1')         && A "C" will be displayed.
   WAIT WINDOW TYPE('m.var2')         && A "U" will be displayed.

   *** End Example Code ***

In a program, the TYPE() function could be used in an IF ... ELSE ... ENDIF scenario, such as:

   *** Begin Example Code ***
   IF TYPE('m.var2')='U'
       WAIT WINDOW 'm.var2 does not exist!'
   ELSE
       WAIT WINDOW 'm.var2 exists!'
   ENDIF

   *** End Example Code ***

Method 2

Set up an ON ERROR routine that will trap for error number 12 (Variable <variable name> not found). For example:

   *** Begin Example Code ***

   m.var1='m.var1 does exist'         && Initialize a variable.
   ON ERROR DO ERRHANDL WITH ERROR()  && Initialize error trapping.
   WAIT WINDOW m.var1       && Display contents of existing variable.
   WAIT WINDOW m.var2       && Display contents of nonexistent variable
                            && that will cause an error.
   ON ERROR                 && Resets ON ERROR routine to default.

   PROCEDURE ERRHANDL                 && PROCEDURE ERRHANDL is the
   PARAMETER errnumbr                 && routine that displays the
   IF errnumbr=12                     && message about the variable
                                      && that does not exist.
      WAIT WINDOW 'The variable you are using does not exist!'
   ENDIF

   *** End Example Code ***

Additional reference words: FoxMac FoxDos FoxWin 2.00 2.50 2.50a 2.50b 2.60 find available found memvar errmsg KBCategory: kbenv kbprg kberrmsg KBSubcategory: FxenvMemory

Last Reviewed: June 27, 1995