从字符串中读取 Lisp 对象

dav*_*ugh 3 string common-lisp

我熟悉从文件中收集 Lisp 对象的基本模板,如下所示:

(with-open-file (stream "filename.lisp")
    (loop for object = (read stream nil 'eof)
          until (eq object 'eof)
          collect object))
Run Code Online (Sandbox Code Playgroud)

但我不确定如何将其转换为从字符串中收集对象,例如使用read-from-string. 那么您是否必须跟踪字符串中停止位置的索引?另外,如何避免与输入中的或eof等任何其他合法 Lisp 对象发生名称冲突?nilt

Bar*_*mar 5

您可以使用with-input-from-string从字符串中读取。

为了防止与符号发生冲突eof,您可以使用未驻留的符号或动态创建的其他对象。

(with-input-from-string (stream "this is a (list of 3 things)")
  (loop with eof-marker = '#:eof
        for object = (read stream nil eof-marker)
        until (eq object eof-marker)
        collect object))
Run Code Online (Sandbox Code Playgroud)