Page 1 of 1

Reading a line using chars

Posted: Tue Feb 19, 2013 2:09 am
by santiago
Hi,

I have this function to read a line using chars. I'm reading chars, because I'm trying to communicate Lisp and Java using sockets and chars.

(def$method (tty-dialog-mixin :babylon-read-string) (&optional special-keys)
(setq X 0)
(setf exit "")
(loop while (<= X 0) do
(let ((char1 (read-char-no-hang *standard-input*)))
(if (eql char1 nil)
(progn
(setq X 1))
(setq exit (concatenate 'string exit (string char1)))
)
)
)
)

but I don't know why always the value of exit is "". I'm trying to update the variable exit with the concatenation of every char received of the socket

Thanks

Re: Reading a line using chars

Posted: Tue Feb 19, 2013 7:16 am
by Goheeca
Why are you not using read-line?

Re: Reading a line using chars

Posted: Tue Feb 19, 2013 9:11 am
by santiago
Hi,

The problem is that I need to read a char, not read-line. I think, Read-line fails because can't find Return.

I've checked this:


(def$method (tty-dialog-mixin :babylon-read-string) (&optional special-keys)
(setq X 0)
(setf exit "")
(loop while (<= X 0) do
(let ((char1 (read-char *standard-input*)))
(cond ((eql char1 nil) (setq X 1))
((eql char1 #\Return) (setq X 1))
((eql char1 #\NewLine) (setq X 1))
((eql char1 #\z) (setq X 1))
(t
(setq exit (concatenate 'string exit (string char1)))
)

)
)
)
)

and works fine If I use the z character after a string in Java..., but I don't know why the read-char can't read #\Return, #\Newline, nil...

I think, that If I change in this loop to check eof of *standard-input*, I'll not need the z character, but I don't know how to do it.

Thanks

Re: Reading a line using chars

Posted: Tue Feb 19, 2013 11:39 am
by sylwester
Calling READ-CHAR-NO-HANG like that you won't know if the function returns NIL because no characters are available or eof.
Eg. (read-char-no-hang) in an interactive session will always return NIL since your keyboard isn't fast enough and the buffer is empty and it return NIL when no char is ready. If you use (read-char-no-hang *STANDARD-INPUT* NIL 'eof) you'll se the symbol eof for end of stream and NIL when there are not char (yet) to read. Making a loop of this will make READ-CHAR so you might as well use (read-char) like this (read-char *STANDARD-INPUT* NIL 'eof), which will return the symbol eof when end of file (stream)

echo '(format t "I got ~A.~%" (read-char *STANDARD-INPUT* NIL "eof"))' > test.lisp
echo -n "t" | clisp test.lisp
I got t.
echo -n "" | clisp test.lisp
I got eof.

Now if you have a process that feeds CL it should work like echo since it's just another process.