Re: Passing Global Variables Urgh.



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.

.



Relevant Pages

  • Bible Quiz (Acts) 22/11/07 Cont.
    ... Reference: Acts 22-26 ... Where did Paul find an altar with the inscription, ... What Christian once lived at Rome, Corinth, and Ephesus? ...
    (uk.religion.christian)
  • Bible Quiz (Acts)
    ... Jesus Christ" in the city of Samaria? ... Reference: Acts 8:12 ... Where did Paul find a certain woman named Lydia? ...
    (uk.religion.christian)
  • ***Bible Quiz (Acts) Cont. 22/11/07
    ... Bible Quiz (Acts) Cont. ... Reference: Acts 22-26 ... Where did Paul find an altar with the inscription, ... What Christian once lived at Rome, Corinth, and Ephesus? ...
    (alt.religion.christian)
  • Bible Quiz (Acts) 24/11/07 Cont.
    ... Bible Quiz (Acts) 24/11/07 Cont. ... Reference: Acts 14:6 ... Come Join the Wrighteous Network Community! ...
    (uk.religion.christian)
  • ***Bible Quiz (Acts) 24/11/07 Cont.
    ... Bible Quiz (Acts) 24/11/07 Cont. ... Reference: Acts 14:6 ... Come Join the Wrighteous Network Community! ...
    (alt.religion.christian)