Keyboard input/Keypress check

From Rosetta Code
Revision as of 18:32, 11 October 2010 by rosettacode>IanOsgood (Forth)
Task
Keyboard input/Keypress check
You are encouraged to solve this task according to the task description, using any language you may know.

Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.

BASIC

ZX Spectrum Basic

<lang basic>10 REM k$ will be empty, if no key has been pressed 20 LET k$ = INKEY$</lang>

Forth

<lang forth>variable last-key

check key? if key last-key ! then ;</lang>

PureBasic

Returns a character string if a key is pressed during the call of Inkey(). It doesn't interrupt (halt) the program flow.

If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey(). <lang PureBasic>k$ = Inkey()</lang>

Tcl

There are two ways to handle listening for a key from the terminal. The first is to put the channel connected to the terminal into non-blocking mode and do a read on it: <lang tcl>fconfigure stdin -blocking 0 set ch [read stdin 1] fconfigure stdin -blocking 1

if {$ch eq ""} {

   # Nothing was read

} else {

   # Got the character $ch

}</lang> The second method is to set up an event listener to perform callbacks when there is at least one character available: <lang tcl>fileevent stdin readable GetChar proc GetChar {} {

   set ch [read stdin 1]
   if {[eof stdin]} {
       exit
   }
   # Do something with $ch here

}

vwait forever; # run the event loop if necessary</lang> Note that in both cases, if you want to get characters as users actually type them then you have to put the terminal in raw mode. That's formally independent of the actual reading of a character.