Differentiating Between Local and Global Variables

AutoCAD Visual LISP

 
Differentiating Between Local and Global Variables
 
 
 

This lesson discusses the use of local variables versus global document variables. Global variables are accessible by all functions loaded within a document (an AutoCAD® drawing). These variables may retain their value after the program that defined them completes. Sometimes, this is what you want. You'll see an example of this later in the tutorial.

Local variables retain their value only as long as the function that defined them is running. After the function finishes running, the local variable values are automatically discarded, and the system reclaims the memory space the variable used. This is known as automatic garbage collection, and is a feature of most LISP development environments, such as VLISP. Local variables use memory more efficiently than global variables.

Another big advantage is that local variables make it easier to debug and maintain your applications. With global variables, you are never sure when or in which function the variable's value might be modified; with local variables you don't have as far to trace. You usually end up with fewer side effects (that is, one part of the program affecting a variable from another part of the program).

Because of the advantages cited, this tutorial uses local variables almost exclusively.

NoteIf you have been working with AutoLISP for some time, you may have developed the practice of using global variables during development to examine your program while you are building it. This practice is no longer necessary, given the powerful debugging tools of VLISP.