3 ms·
In Lisp, you should use a global variable when you need a persistent module-level state, and let your defun forms be top-level forms: ;; bad (let ((s (make
by kazinator 10y ago
In Lisp, you should use a global variable when you need a persistent module-level state, and let your defun forms be top-level forms:
;; bad
(let ((s (make-state-thing)))
(defun function () ...)))
;; good
(defparameter *s* (make-state-thing))
(defun function () ...)
That defparameter might be defvar: it depends on whether you want to re-initialize the state variable when a new version of this module is loaded, or keep the old value.
Speaking of which, with the let, you don't get that decision. For the defun to have its effect, the form has to be evaluated. Every evaluation of the let instantiates a new binding for s in a new lexical environment, end of story.
Even if we have the defparameter, we can redefine function while keeping the same state.
It's also easy to inspect the state. A the REPL, just evaluate its name: there it is. You don't have to whip out a closure environment inspector.
defun is a "stone age" tool anyway, which destructively overwrites a global function binding. Wrapping it with a captured lexical environment is a form of situational irony in programming (if not indeed verbal).