help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: loading hash-table from a file?


From: Eric Abrahamsen
Subject: Re: loading hash-table from a file?
Date: Thu, 05 Jan 2012 17:07:15 +0800
User-agent: Gnus/5.110018 (No Gnus v0.18) Emacs/24.0.92 (gnu/linux)

On Thu, Jan 05 2012, ishi soichi wrote:

> I have never used hash-table of Emacs Lisp but I believe it's useful
> as a database.
>
> Say, I have a hundred key-value pairs, which are to be stored as
> hash-table. 
> Can I save this as a (text?) file so that Emacs can load it when
> booting up?
>
> I am a little confused because if I use (cons key value), it outputs
> "(key . value)" which can be written in a regular file.
> If I wish to find the value from a key, all I need to do is to simply
> search through the file.
>
> Do you think I can save the database using hash-table like this?
>
> soichi
>
>

I found this on the internet (presumably authored by someone with the
initials T.V.), which does what you're asking (I used it to persist a
hash-table that I load on startup). I don't really know if it's superior
to the previous reply, but it certainly works. It produces a *.elc file,
which can be loaded with `load' (provided it's in your load-path, of
course). Whatever symbol name you originally dumped then becomes defined
again.

Eric

--8<---------------cut here---------------start------------->8---
(defun tv-dump-object-to-file (obj file)
  "Save symbol object `obj' to the byte compiled version of `file'.
 `obj' can be any lisp object, list, hash-table, etc...
 `file' is an elisp file with ext *.el.
 Loading the *.elc file will restitute object."
  (require 'cl) ; Be sure we use the CL version of `eval-when-compile'.
  (if (file-exists-p file)
      (error "File already exists.")
    (with-temp-file file
      (erase-buffer)
      (let* ((str-obj (symbol-name obj))
             (fmt-obj (format "(setq %s (eval-when-compile %s))" str-obj 
str-obj)))
        (insert fmt-obj)))
    (byte-compile-file file) (delete-file file)
    (message "`%s' dumped to %sc" obj file)))
--8<---------------cut here---------------end--------------->8---


-- 
GNU Emacs 24.0.92.2 (i686-pc-linux-gnu, GTK+ Version 2.24.8)
 of 2012-01-04 on pellet




reply via email to

[Prev in Thread] Current Thread [Next in Thread]