This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
BlankTitle's profile picture

How to wait for keystrokes

Started by BlankTitle, 14 May 2013 - 06:16 PM
BlankTitle #1
Posted 14 May 2013 - 08:16 PM
Introduction:

Using events to wait for keystrokes can be useful in many situations, such as waiting for a user to type before display new text. In the next few paragraphs I will demonstrate how to make a code like this and provide a few examples

Setting up the code:
Here we will start with a blank program:

In order to start, we need to make an event:
 local event, keystroke = os.pullEvent("char")

Next we will setup a specific keystroke requirement:
 if keystroke == "q" then
--code here
else
--code here
end

Now lets fill this with code to show some of its uses.
print("Press Q to continue")
local event, keystroke = os.pullEvent("char")
if keystroke == "q" then
print("You pressed the q key")
else
print("You pressed the wrong key")
term.clear()
end

You can also have a code to clear the screen after hitting a key:
print("Press Q to erase data")
local event, keystroke = os.pullEvent("char")
if keystroke == "q" then
term.clear()
print("Data Erased")
os.shutdown()
else
print("Data Persists")
end

How this code works:

In this code we call an event waiting for a key to be pressed. The code will wait for a key press then execute the next line of code. In these examples I used a code requiring you to press a certain key, but you can remove this to simply use a key to perform the next snippet of code.

Thanks,


BlankTitle

P.S. If you find any errors in this code please notify me!
PixelToast #2
Posted 14 May 2013 - 08:55 PM
good tutorial, next you need os.pullEvent("key") to catch enter and such
Kingdaro #3
Posted 14 May 2013 - 09:00 PM
Yeah, like PixelToast said, it's generally bad practice to use the char event alone to detect keypresses. The char event is good for making a typeable field, though, like in the read() function.
BlankTitle #4
Posted 14 May 2013 - 09:04 PM
Thanks you guys for the tips!