如何在 LispWorks 中正确询问用户的输入?

问题描述

我有这个代码

(defvar x)
(setq x (read))
(format t "this is your input: ~a" x)

它在 Common Lisp 中有点工作,但 LispWorks 显示错误

End of file while reading stream #<Synonym stream to
*BACKGROUND-INPUT*>.

我的意思是我试过这个:How to read user input in Lisp 创建一个函数。但仍然显示相同的错误

我希望任何人都可以帮助我。

解决方法

你可能把这三行写进编辑器然后编译了。

因此,您可以将此函数写入编辑器:

(defun get-input ()
  (format t "This is your input: ~a" (read)))

编译编辑器并从侦听器 (REPL) 调用此函数。

CL-USER 6 > (get-input)
5
This is your input: 5
NIL

您也可以像这样使用 *query-io* 流:

(format t "This is your input: ~a" (read *query-io*))

如果您在 Listener 中调用此行,它的行为类似于 read。如果你在编辑器中调用它,它会显示小提示“输入内容:”。

如您所见,不需要全局变量。如果您需要对该给定值执行某些操作,请使用 let,它会创建本地绑定:

(defun input-sum ()
  (let ((x (read *query-io*))
        (y (read *query-io*)))
    (format t "This is x: ~a~%" x)
    (format t "This is y: ~a~%" y)
    (+ x y)))

还考虑使用 read-line,它接受​​输入并将其作为字符串返回:

CL-USER 19 > (read-line)
some text
"some text"
NIL

CL-USER 20 > (read-line)
5
"5"
NIL