mparsa wrote:Hi,
Can we define global variable in lisp !? If we have it in lisp, how we can define it ?
- Code: Select all
(defvar foo 3)
Creates a global variable and assings it the value 3.
- Code: Select all
(defvar foo 3 "This is foo, which should be 3")
Does the same, but associates a docstring to it, which will be shown if you (inspect 'foo) or (describe 'foo). Useful if you're working with a lot of files because you don't have to dig the definition of foo up to see if you left any comments there.
After you've created a variable with defvar, it's best to use setter functions (Setf or setq) to change it's value, as some implementations allow changing the value of global variables by calling defvar again, but others don't.
If you want to get rid of your variable in some way, you can
- Code: Select all
(unintern 'foo)
If you've defined foo in one package, you need to use some special syntax to get it from another package:
- Code: Select all
(in-package :CL-USER)
(defvar foo 3)
(defpackage (:MY-PACK
(:use :CL))
(in-package :MY-PACK)
(eql cl-user:foo 3)
Should return T
Many packages only export a limited number of symbols. If the variable you need is not exported, you can retrieve it in the following way:
- Code: Select all
(defpackage :protected-test
(:use :CL :CL-USER)
(:export :baz)
(in-package :protected-test)
(defvar baz 3)
(defvar foo 4)
(in-package :CL-USER)
(eql protected-test:baz 3)
(eql protected-test:foo 4)
(eql protected-test::foo 4)
The one-to-last line will give an error, because protected-test does not export foo, so you can't access it like that. The last line does work though, because you're using the double semicolon to indicate that you do want to access the protected variable. It's usually bad form to access variables that are not exported, they're not exported for a reason.