I am writing a text game in Clojure. I want the player to type lines at the console, and the game to respond on a line-by-line basis.
Research showed me that (read-line)
is the way one is meant to get text lines from standard input in Clojure, but it is not working for me.
I am in a fresh Leiningen project, and I have added a :main
clause to the project.clj
pointing to the only source file:
(ns textgame.core)
(defn -main [& args]
(println "Entering -main")
; (flush) ;makes no difference if flush are commented out
(let [input (read-line)]
(println "ECHO:" input))
; (flush)
(println "Exiting -main"))
using lein run
yields:
Entering -main
ECHO: nil
Exiting -main
In other words, there is no opportunity to enter text at the console for (read-line)
to read.
How should I get Clojure to wait for characters and newline to be entered and return the corresponding string?
(I am using GNOME Terminal 2.32.1 on Linux Mint 11, Leiningen 1.6.1.1 on Java 1.6.0_26 Java HotSpot(TM) 64-Bit Server VM, Clojure version 1.2.1.)
Update: If I run lein repl
, I can (println (read-line))
, but not when I have a -main
function and run using lein run
.
I have had similar problems and resorted to building a jar file and then running that.
It's a bit slower, though it got me unstuck. An answer that works from the repl would be better
Wrap your read-line calls with the macro with-read-line-support which is now in ns swank.core [since swank-clojure 1.4+ I believe]:
Thanks to Tavis Judd for the fix.
Try "lein trampoline run". See http://groups.google.com/group/leiningen/browse_thread/thread/a07a7f10edb77c9b for more details also from https://github.com/technomancy/leiningen:
Not sure about the lein aspects of the problem, but definitely in emacs it is impossible to make stdin work. However, if you want to get text from the user, you can easily do it using a JOptionPane like this code from my little tic-tac-toe program: