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

Repeat until user input

Started by SNWLeader, 27 November 2012 - 04:38 PM
SNWLeader #1
Posted 27 November 2012 - 05:38 PM
I want to make a program that repeats a function until a person presses a key or mabye even types something. I am making a program that is compatible with a wheat harvester.

What I am looking for is that when I run the program the program will not stop until I press any key.
Orwell #2
Posted 27 November 2012 - 05:52 PM
My quick and dirty technique is the following:

local function yourFunction()
  -- loop here
end

parallel.waitForAny(yourFunction, function() os.pullEvent('key') end)
This will run yourFunction until it returns or a key is pressed.
KaoS #3
Posted 28 November 2012 - 03:18 AM

while os.pullEvent()~='key' do
  --your code
  os.startTimer(loop delay)
end
SNWLeader #4
Posted 29 November 2012 - 02:59 PM

while os.pullEvent()~='key' do
  --your code
  os.startTimer(loop delay)
end
that one does not work for some reason.
SNWLeader #5
Posted 29 November 2012 - 03:05 PM
I figured one out.

repeat
----code wanting to repeat
until os.pullEvent() = 'key'
ChunLing #6
Posted 30 November 2012 - 09:54 AM
Yes, but yours will stall unless the code you repeat generates events (which apparently it does). Kaos' "os.startTimer(loop delay)" prevents that, but you need to replace "loop delay" with a numeric value indicating the maximum time you'll pause before starting the next iteration of the loop. I agree with your use of repeat…until rather than while ~= do…end, it is structurally more appropriate to the particular task at hand. If the code you've inserted is such that it generates/receives sufficient events to keep the loop running, then that is all well and good.

I fear that you're pulling and discarding at least some events that you actually want to use, though.
KaoS #7
Posted 30 November 2012 - 10:01 AM
you are most correct on the use of the repeat until loop, I derped out there :)/> you shouldn't lose any timers, perhaps rednet messages if you get them at the wrong time but if you want to use os.pullEvent() in your code let us know and we will give you an adaptation
SNWLeader #8
Posted 30 November 2012 - 06:00 PM
Ya I had to add the os.startTimer(loopdelay)
the program would run the desired code once then stop working the os.startTimer(loopdelay) fixes that.