0

我想检索由生成的字符串以write进行进一步处理而不进行任何实际输出,但write似乎总是也输出到 REPL

CL-USER>(let ((err-string (write (make-instance 'error) :stream nil)))
          (do-awesome-stuff-with-string err-string))
<ERROR> ;;this is the printing I want to get rid of
"awesome-result"

为什么write仍然输出到 REPL,我该如何摆脱它?

4

2 回答 2

6

你可以用with-output-to-string这个。这是一个例子:

(flet ((do-awesome-stuff-with-string (string)
         (concatenate 'string string " is awesome!")))
  (let ((err-string (with-output-to-string (s)
                      (write (make-instance 'error) :stream s))))
    (do-awesome-stuff-with-string err-string)))
;; => "#<ERROR {25813951}> is awesome!"

这是HyperSpec上的条目with-output-to-string

(write (make-instance 'error) :stream nil)不起作用的原因是:stream参数 towrite流指示符,在这种情况下nil*standard-output*. (format相反nil,它意味着它应该返回一个字符串,这是一个常见的混淆点)。

于 2013-10-13T01:48:20.700 回答
3

请记住,可移植的错误是由MAKE-CONDITION. 该标准没有说错误是 CLOS 类,因此MAKE-INSTANCE在某些实现中可能不起作用。

获取字符串有两种简单的方法:

a) 文字描述:

CL-USER 15 > (princ-to-string (make-condition 'error))
"The condition #<ERROR 4020311270> occurred"

b) 打印的错误对象:

CL-USER 16 > (prin1-to-string (make-condition 'error))
"#<ERROR 402031158B>"
于 2013-10-13T12:07:19.390 回答