其实你可以*standard-output*
直接绑定:
(defun test-im-vs-ex-plicit ()
(values
(with-output-to-string (*standard-output*) ; here
(implicit))
(with-output-to-string (stream)
(explicit stream))))
没有真正简单的答案。我的建议:
使用流变量,这使得调试更容易。它们出现在参数列表中,并且更容易在回溯中发现。否则,您需要在回溯中查看流变量的动态重新绑定。
a) 没有什么可以通过的?
(defun print-me (&optional (stream *standard-output*))
...)
b) 一个或多个固定参数:
(defun print-me-and-you (me you &optional (stream *standard-output*))
...)
c) 一个或多个固定参数和多个可选参数:
(defun print-me (me
&key
(style *standard-style*)
(font *standard-font*)
(stream *standard-output*))
...)
还要注意这一点:
现在假设(implicit)
有一个错误,我们得到一个中断循环,一个调试repl。这个中断循环中标准输出的价值是什么?
CL-USER 4 > (defun test ()
(flet ((implicit ()
(write-line "foo")
(cerror "go on" "just a break")
(write-line "bar")))
(with-output-to-string (stream)
(let ((*standard-output* stream))
(implicit)))))
TEST
CL-USER 5 > (compile 'test)
TEST
NIL
NIL
CL-USER 6 > (test)
Error: just a break
1 (continue) go on
2 (abort) Return to level 0.
3 Return to top loop level 0.
Type :b for backtrace or :c <option number> to proceed.
Type :bug-form "<subject>" for a bug report template or :? for other options.
CL-USER 7 : 1 > *standard-output*
#<SYSTEM::STRING-OUTPUT-STREAM 40E06AD80B>
CL-USER 8 : 1 > (write-line "baz")
"baz"
CL-USER 9 : 1 > :c 1
"foo
baz
bar
"
以上是您在 LispWorks 或 SBCL 中看到的内容。在这里您可以访问真实程序的绑定,但在调试期间使用输出函数会对该流产生影响。
在其他实现*standard-output*
中将反弹到实际终端 io - 例如在 Clozure CL 和 CLISP 中。
如果您的程序没有重新绑定*standard-output*
,那么这些情况下的混乱就会减少。如果我编写代码,我经常会考虑在 REPL 环境中什么会更有用——这与语言不同,在 REPL 和中断循环上的交互式调试较少......