emacs lisp 中的惯用方式序列化

Seb*_*_學生 7 lisp emacs elisp

目前我正在研究一种跨会话使用哈希表的 elisp 主要模式。所以每次初始化主模式时,表都会加载到内存中。在会话期间和结束时,它们被写入文件。我当前的实现以下列方式写入数据:

(with-temp-buffer
  (prin1 hash-table (current-buffer))
  (write-file ("path/to/file.el"))))
Run Code Online (Sandbox Code Playgroud)

在会话开始时加载数据是通过读取完成的,是这样的:

(setq name-of-table (car
        (read-from-string
         (with-temp-buffer
           (insert-file-contents path-of-file)
           (buffer-substring-no-properties
        (point-min)
        (point-max))))))))
Run Code Online (Sandbox Code Playgroud)

它有效,但我觉得这不是最漂亮的方法。我的目标是:我希望这个主要模式变成一个漂亮的干净包,将它自己的数据存储在存储包的其他数据的文件夹中。

tom*_*tom 4

这就是我的实现方式

写入文件:

(defun my-write (file data)
  (with-temp-file file
    (prin1 data (current-buffer))))
Run Code Online (Sandbox Code Playgroud)

从文件中读取:

(defun my-read (file symbol)
  (when (boundp symbol)
    (with-temp-buffer
      (insert-file-contents file)
      (goto-char (point-min))
      (set symbol (read (current-buffer))))))
Run Code Online (Sandbox Code Playgroud)

打电话写:

(my-write "~/test.txt" emacs-version)
Run Code Online (Sandbox Code Playgroud)

来电阅读

(my-read "~/test.txt" 'my-emacs-version)
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 `(goto-char (point-min))` 后跟 `(read (current-buffer))`,这样您就不必创建字符串。 (2认同)