Keyboard input/Keypress check: Difference between revisions

From Rosetta Code
Content added Content deleted
(Apply the Terminal Control semantic property, as a task.)
(Add input device as a semantic property. Note that this isn't terminal control, but a form of user input. (And I should pay more attention to my open tabs!))
Line 1: Line 1:
{{task}}
{{task}}


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.
Determine if a [[Input device::keyboard|key]] has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
[[Terminal Control::task| ]]
[[user input::task| ]]

=={{header|BASIC}}==
=={{header|BASIC}}==



Revision as of 01:43, 19 October 2010

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>

<lang logo>if key? [make "keyhit readchar]</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.