Hello,
is there any way to detect keyboard input using Nim? Something like this:
echo "What do you want to do?"
echo "1) Do something"
echo "2) Exit"
echo "Press '1' or '2' on your keyboard"
I don't want to have to press ENTER after entering my choice like in this example
echo "What do you want to do?"
echo "1) Do something"
echo "2) Exit"
var choice = readLine(stdin)
case choice:
of "1":
echo "Chosen 1"
of "2":
echo "Chosen 2"
I would like to automatically detect "1" or "2" on your keyboard. Thanks for help!
I believe the Unix & similar way to do this is "CBREAK mode" on the terminal/tty device, but under Windows there is a totally different mechanism. I do not believe the Nim stdlib abstracts over these possibilities.
So, sorry to answer your question with a question, but I believe the answer to your question depends on if you are you willing to have this work on a subset of operating systems, and if so which subset?
@Stefan_Salewski is right - terminal.getch does abstract over OSes after all, though only (Windows & posix it looks like). So this code should work:
import terminal
echo """What do you want to do?
1) Do something
2) Exit"""
case getch():
of '1': echo "Chosen 1"
of '2': echo "Chosen 2"
else: echo "invalid choice; bye"; quit(1)
Some notes - getch() returns a char. So, single quotes on the case of's. Nim requires covering all cases. So, you need an else:. And I did a triple quoted string prompt just for kicks.