3

我有一个循环:

(defun echo-lines ()
  (loop while 
        (let ((line (read-line)))
           (if (equal line "done")
               nil
               (print line)))))

我希望它在用户结束行后回显用户的输入,除非他们输入了“完成”,在这种情况下它会停止。相反,它第一次回显一个空行,之后,它回显前一个的输入。例子:

* (echo-lines)
Hello, loop.

This is my second line.
"Hello, loop." 
This is my third.
"This is my second line." 
I'm almost done.
"This is my third." 
done
"I'm almost done." 
NIL

预期的:

* (echo lines)
Hello, loop.
"Hello, loop."
done
NIL
4

1 回答 1

7

该效果是由缓冲输出和PRINT.

PRINT如果底层输出流被缓冲,则不会导致立即写入输出。另请注意,首先PRINT打印换行符。请注意,对于可移植代码,您应该假设输出流是缓冲的。这意味着您需要确保在需要时写入缓冲输出。使用(不等待)和(等待)。FORCE-OUTPUTFINISH-OUTPUT

这是一个稍微改写的版本。

(defun echo-lines ()
  (loop for line = (read-line)
        until (equal line "done")
        do
        (write-line line)
        (finish-output)))
于 2012-11-18T22:46:23.283 回答