Get a pointer to a list item in Emacs Lisp

For example, I have a list:

(setq foo '(1 2 3 4 5))

Then I need to get a pointer to its third index element (which contains 4in the example):

(setq p (SOME_FUNCTION foo 3))

An item with address p can be moved to another list, so I cannot just save its current index foo.

And I will need to say later:

(push 0 foo)
=> (0 1 2 3 4 5)
(setf p 444)

and the list fooshould be (0 1 2 3 444 5)after.

Is this possible in Emacs lisp?

+5
source share
2 answers

In general, you cannot save the "address" of an object. However, you can refer to the cons cell (the cons cell is what the lists are made of). After that, the cons cell could be changed with setcarand setcdr.

For instance:

(defvar my-cons-cell nil)

(defun my-save-cons-cell (cons-cell)
  (setq my-cons-cell cons-cell))

(defun my-set-car-in-saved-cons-cell (value)
  (setcar my-cons-cell value))

;; Test

(setq foo '(1 2 3 4 5))

(my-save-cons-cell (cdr (cdr (cdr foo))))

(push 0 foo)

(my-set-car-in-saved-cons-cell 444)

foo (0 1 2 3 444 5).

, lisp ...

+6

(setq p (nth 3 foo))

p , .

(setf (nth 3 foo) 444)

444 . -

(setq pointer (nth 3 foo))
...
(setf pointer 444)

. Emacs gv-ref gv-deref, . C & *:

(setq pointer (gv-ref (nth 3 foo)))
...
(setf (gv-deref pointer) 444)
+3

All Articles