The effect that (eval counter)
increments counter
in some sense can be reached by setting counter
to a quoted closure call.
The eval
evaluates the closure, the closure captures the actual counter and increments it at the eval
. This solution does not address the setq
part of your question.
There follows example code together with usage instructions.
Put the following code into an elisp file (e.g., /tmp/test.el
under Linux) and run emacs-lisp-byte-compile-and-load
on that file (menu item Emacs Lisp > Byte-compile and Load).
;;; -*- lexical-binding: t -*-
(let ((counter_value 0))
(defun counter-fun () (cl-incf counter_value)))
(defvar counter '(counter-fun))
Put (eval counter)
into the *scratch*
buffer and evaluate it.
The first call gives 1 the second 2 and so on.
The code is tested with emacs-version
25.1.50.2.
Note, that it is even not necessary to put the incrementation of counter_value
into a closure. You can also use (defvar counter_value 0)
and the defun
on top-level. Nevertheless the closure serves for information hiding. counter_value
can only be accessed through counter
in the version above.
(eval counter)
instead of justcounter
- why the double evaluation? – Drew Mar 23 '18 at 17:11cl-symbol-macrolet
), but it doesn't. Why would a newbie to the language ask for a very specific solution to a problem better solved in a different way? – wasamasa Mar 23 '18 at 20:55counter
here instead of a (nullary) function(counter)
? – Drew Mar 27 '18 at 14:56