Hi,
Can we define global variable in lisp !? If we have it in lisp, how we can define it ?
Can we define global variable in lisp !? If we have it in lisp, how we can define it ?
Discuss and learn Lisp programming of all dialects
This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.
4 posts · 3746 views
mparsa wrote:Hi,Hi mparsa,
Can we define global variable in lisp !? If we have it in lisp, how we can define it ?
mparsa wrote:Hi,
Can we define global variable in lisp !? If we have it in lisp, how we can define it ?
(defvar foo 3)
Creates a global variable and assings it the value 3.(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.(unintern 'foo)
If you've defined foo in one package, you need to use some special syntax to get it from another package:(in-package :CL-USER)
(defvar foo 3)
(defpackage (:MY-PACK
(:use :CL))
(in-package :MY-PACK)
(eql cl-user:foo 3)
Should return T(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.