我是Lisp的新手,想知道:有没有办法列出所有(用户定义的)全局变量?
一种可能性是检查包的哪些符号是boundp
:
(defun user-defined-variables (&optional (package :cl-user))
(loop with package = (find-package package)
for symbol being the symbols of package
when (and (eq (symbol-package symbol) package)
(boundp symbol))
collect symbol))
它返回未从另一个包继承的绑定符号的列表。
CL-USER> (user-defined-variables) ; fresh session
NIL
CL-USER> 'foo ; intern a symbol
FOO
CL-USER> (defun bar () 'bar) ; define a function
BAR
CL-USER> (defparameter *baz* 'baz) ; define a global variable
*BAZ*
CL-USER> (user-defined-variables)
(*BAZ*) ; only returns the global variable