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

Waiting for a specific keypress?

Started by Ind0ctr1n3, 18 May 2013 - 05:55 PM
Ind0ctr1n3 #1
Posted 18 May 2013 - 07:55 PM
If I may inquire something similar;

I'm trying to create a program ending which triggers when the user presses a button.

For example;

while true do

local time = os.time()

print ("Tick: " ..time)

event, param1 = os.pullEvent()
if event == "char" and param1 == "e"
break

sleep(1)

end

Which will indeed end the program after 'e' is pressed, but it will regardless interrupt the program waiting for user input.

What I would like to know is how to tell the program that if it detects NO input, it should just continue on with the program. (Just keep refreshing the time until interrupted)

Thank you in advance!
Lyqyd #2
Posted 19 May 2013 - 02:52 AM
Split into new topic. There is a sticky specifically for new members to use to ask new topics, which you should have posted in instead.
theoriginalbit #3
Posted 19 May 2013 - 03:33 AM
The easiest thing for you to do is use a timer. A timer will fire an event when it is complete. Also using this timer and the pull event would remove the need for the sleep(1) in your code.

Using the timer would end with something like this


--# this is our timeout variable, this will cause the pull event to return and continue running the loop after 1 second has passed
local timeout = os.startTimer(1)
--# setup the time variable
local time = os.time()
--# initial time print, read comment in loop below to see why
print('Tick: '..time)

while true do
  local event, param = os.pullEvent()
  if event == 'char' and param == 'e' then
	break
  --# if the event was fired was a timer, and the id of the timer that finished is the same as our timeout timer id
  elseif event == 'timer' and param == timeout then
	--# restart our timer
	timeout = os.startTimer(1)
	--# update the time
	time = os.time()
	--# print the time here, why? that way if someone spams a key it doesn't spam print the time, the time will only update on the timer finishing
	print('Tick: '..time)
  end
end