Ted Kosan ted.kosan@gmail.com writes:
I am currently working through the "Land of Lisp" book by Conrad Barski and I am using ABCL to run all of the code in the book. In the following code, the prompt that is printed by 'print'
No. This is a misconception. PRINT doesn't print anything. It's FORCE-OUTPUT that does.
is not seen until after 'read' returns:
Of course, since you didn't issue any FORCE-OUTPUT. Now, in the case of interactive I/O, you may want to use FINISH-OUTPUT instead of FORCE-OUTPUT. FINISH-OUTPUT calls FORCE-OUTPUT and then waits for the output to be completed, thus ensuring that the reading doesn't start before the prompt is written. You should even call CLEAR-INPUT before read, to ensure that all input before the READ is discarded.
(defun add-five() (print "Pleaser enter a number:") (let ((num (read))) (print "When I add five I get") (print (+ num 5))))
Is it possible to configure ABCL to have the output from 'print' be visible immediately so that it can be used to prompt the user to input some information?
Conforming interactive code should be written as:
(defun add-five () (terpri) (princ "Pleaser enter a number: ") (finish-output) (clear-input) (let ((num (read))) (terpri) (princ "When I add five I get ") (princ (+ num 5)) (terpri) (terpri) (force-output)) (values))
CL-USER(4): (add-five) 42
Pleaser enter a number: 11
When I add five I get 16
CL-USER(5):
Notice: with slime, the 42 might be retained by slime, and send after to swank for evaluation, so it might still be read by swank REPL after the function add-file having cleared the input returns.