Re: Is there ever a good reason to create globals in Lisp?

"Pascal J. Bourguignon" <[email protected]>
Newsgroups gmane.lisp.clisp.devel
Organization InformatiMago.
Message-ID <[email protected]>
"Yves S. Garret" <[email protected]> writes:

> Hi, going through Land of Lisp and I get to a part of the book where
> you define global variables.  I realize that the author is trying to
> educate the students about this, but is there ever a good reason for
> globals in Lisp?  In Java, C/C++, PHP, etc. it's frowned down upon at
> best.

Functions, classes, types, constants, packages, etc,  are global
bindings.

There are so many things that have global names, why do you worry about
a few global variables?


Yes, there are good reasons to have global variables.

The main one is to keep references to "persistent" data.  The scope of
persistence being that of the lisp image (and remember that
implementations provide operators to save the lisp images and reload
them).

Given the REPL, global variables allow passing data between two
functions called independently, and with the programmer intervention at
the REPL in the middle.


    cl-user> (defvar *data*)
    *data*
    cl-user> (defun compute-phase-a () (setf *data* (random 42)))
    compute-phase-a
    cl-user> (defun compute-phase-b () (* 2 *data*))
    compute-phase-b
    cl-user> (compute-phase-a)
    40
    cl-user> *data*
    40
    cl-user> (compute-phase-b)
    80
    cl-user> *data*
    40


Also, in Common Lisp global variables defined with defvar and
defparameter are special variables.  All the bindings involving the
symbol naming them are dynamic bindings.  This allow passing pervasive
parameter unconspicuously. 

    cl-user> (defun do-something () (print *data*) (terpri))
    do-something
    cl-user> (setf *print-base* 16.)
    10
    cl-user> (do-something)

    28 
    nil
    cl-user> (setf *print-base* 10.)
    10
    cl-user> (do-something)

    40 
    nil



-- 
__Pascal Bourguignon__                     http://www.informatimago.com/
A bad day in () is better than a good day in {}.

------------------------------------------------------------------------------
Live Security Virtual Conference
Exclusive live event will cover all the ways today's security and 
threat landscape has changed and how IT managers can respond. Discussions 
will include endpoint security, mobile security and the latest in malware 
threats. http://www.accelacomm.com/jaw/sfrnl04242012/114/50122263/
_______________________________________________
clisp-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/clisp-devel
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.