Re: Passing Global Variables Urgh.
- From: Geoff Wozniak <geoff.wozniak@xxxxxxxxx>
- Date: Wed, 29 Aug 2007 16:52:19 -0700
On Aug 29, 7:28 pm, landspeedrecord <landspeedrec...@xxxxxxxxx> wrote:
First off... I know I am not supposed to use global variables in Lisp,
however...
Why not? They can be very handy.
Can anyone explain to me why the following bit of code doesn't work?
I don't get it and I think it is because there is something very
fundamental I do not understand about Lisp.
Variables are passed by values, not by reference. Thus,
(defun test2 (x)
(setq x "orrgoaarghhh"))
sets the value of the parameter X, not what was passed to it. If you
need to adjust parameters in the way you were expecting, you can use a
macro, but I doubt that's what you want to do.
One way to deal with this is to wrap the value in a cons cell, which
acts as a reference. Similar effects can be achieved using structures
and classes.
CL-USER> (defparameter *x* (cons "yay!" nil))
*X*
CL-USER> (defun test (x) (setf (car x) "my value"))
TEST
CL-USER> (car *x*)
"yay!"
CL-USER> (test *x*)
"my value"
CL-USER> (car *x*)
"my value"
My only guess is that the function "test2" gets passed a copy of the
global variable that is exists inside the function "test2". But isn't
the whole point of Defvar & Defparameter to create a global variable
that can be accessed from anywhere? If a copy of a global variable is
always passed into functions what good is a global variable?
In your example, you weren't setting the global(*) variable *X*, you
were setting the local parameter X.
(*) It's really called a special variable.
.
- References:
- Passing Global Variables Urgh.
- From: landspeedrecord
- Passing Global Variables Urgh.
- Prev by Date: Re: Passing Global Variables Urgh.
- Next by Date: Re: Floyd Warshall
- Previous by thread: Re: Passing Global Variables Urgh.
- Next by thread: Re: Passing Global Variables Urgh.
- Index(es):
Relevant Pages
|