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

How to receive user input in a for loop without stopping loop

Started by TheJusta, 25 May 2013 - 12:07 AM
TheJusta #1
Posted 25 May 2013 - 02:07 AM
Hey guys, I'm new to computercraft and Lua but I'm actually experienced with Java and I need some help with this program I'm working on.

I'm doing a self-destruct program that asks the user to set a time (in seconds) for the self-destruction. It uses a for-loop to increment the variable up to the selected time with a sleep method to space out the increments. While the for loop is looping I want the user to be able to press any key on the keyboard to pause the loop and input a password that if entered correctly shuts down the computer or else continues the loop. I've got everything right except when I run the program the pullEvent automatically waits for input instead of activating if there is an input from the keyboard. So the countdown goes 1 and stops, then if I press a key I'm prompted to enter the password, if I input the wrong password it goes on to 2 and so on until it reaches the limit and sets off the bomb. What can I do to activate the last if clause only if input is received? Here is my code:

write("Set time for autodestruct(seconds)")
local Num = tostring(read())
write("Timer: \n")
local password = nil
local terminate = 0
redstone.setOutput("back", true)
for i=1, Num do
	  write(tostring( i.. "\n"))
	  sleep(1)
			  if os.pullEvent("char") then
					 print("Enter password to stop sequence")
					 password = read()
							  if password == "stop" then
							  os.shutdown()
							  end
			   end
end
redstone.setOutput("top", true)

The code works fine, bomb sets off if I manually go through every loop and the computer shuts down if I enter the right password. The only hitch is really that pullEvent…

Thanks for the help!
Lyqyd #2
Posted 25 May 2013 - 03:16 PM
Split into new topic.

Your timing loop should look a bit like:


os.startTimer(1)
while true do
  event = os.pullEvent()
  if event == "timer" then
    --handle the timer events (replaces the sleep)
    os.startTimer(1)
  elseif event == "key" then
    --handle the keypresses
    --probably need another startTimer here unless you want to manually handle password input rather than using read()
  end
end