Loading and saving uLisp functions to a file


#1

Hi,

at the uLisp page there’s a function to load uLisp functions from a file. It looks rather similar to:

(defun load (filename)
    (with-sd-card (s filename)
       (loop
          (let ((line (read s))) 
             (if (null line) (return (globals)) (eval line))))))

Now I wrote a function to save the whole environment to a textfile:

(defun save (fn)
  (princ "Saving:")
    (with-sd-card (str fn 2)
      (mapcar
        (lambda (n)
           (princ " ") (princ n)
           (princ "(defvar " str)
           (princ n str)
           (princ " '" str)
           (pprint (eval n) str)
           (princ ")" str)
           (terpri str) (terpri str))
        (globals)))
 nothing)

You can test these functions with:

(defvar data '(1 4 9 16 25 36 49))
(defvar four 4)
((defun fac (n) (if (< n 2) 1 (* n (fac (- n 1)))))
(save "test.lsp")

Restart the board, then:

(require 'load)  -- I stored this function in my LispLibrary
(load "test.lsp")
(globals) -- returns (save fac data four)
four      -- returns 4
data      -- returns (1 4 9 16 25 36 49)
fac       -- returns (lambda (n) (if (< n 2) 1 (* n (fac (- n 1)))))

The formatting in the created file is not perfect, but it is working and the functions and variables can be read back using (load).
So you can develop a few functions with uLisp and save your work in a textfile, which will not depend on the version of uLisp used (as images are).
If ‘resetautorun’ is defined in your uLisp version you can create a small image to load the rest of the code from textfiles at systemstart.
Comments are welcome!

As I am a lisp newby, what do you think about the code of (save) (it took me a while to get it working ;-) )?
How would be the ‘lispy’ way of writing the function (save)?

Best regards,
Klaus