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

[Lua][Problem]

Started by Salaveneus, 19 October 2012 - 06:51 PM
Salaveneus #1
Posted 19 October 2012 - 08:51 PM
So I have been working on an automatic shutdown program, I have made alot of progress on it, but now I am encountering a problem.

I want the program to run in the background continously, so when I asked how to do this, I was told to use parallel API, now I have tried and tried again to do it, but I am not really sure what is wrong with my code at this point, I don't know much about Parallel, and functions, except the very basics, so if someone could take a look at my code and see what is wrong, that'd be great. The program works if you don't enter a character, but the second you enter a character, the program wont shutdown even after the wait period. The way I want to do this is have after say 5 minutes (I am using 5 seconds in my code just to make it easier to test =P) of no registered key press, the program shuts down the computer.


function shutdown()
  os.pullEvent = function(filter)
   local timer = os.startTimer(5)
   local evt, p1, p2, p3, p4, p5 = os.pullEventRaw()
	 if evt == "terminate" then
				    error("Terminate")
	  if evt == "timer" and p1 == timer then
		   os.shutdown()
   end
   timer = os.startTimer(5)
   return evt, p1, p2, p3, p4, p5
  end
end
local function function2()
  shell.run("rom/programs/shell")
end
parallel.waitForAny (shutdown, function2)
faubiguy #2
Posted 19 October 2012 - 09:14 PM
Instead of redefining os.pullEvent, you can make the shutdown function itself check for timers and keypresses:
function shutdown()
    local timer = os.startTimer(5)
	while true do
		local evt, p1 = os.pullEvent()
		if evt == "timer" and p1 == timer then
			os.shutdown()
		elseif evt == "key" then
			timer = os.startTimer(5)
	end
end
ChunLing #3
Posted 19 October 2012 - 09:25 PM
Doesn't this pull all the events and make it so that the computer is doomed to eventually shutdown? How about if a key press exited the loop?
faubiguy #4
Posted 19 October 2012 - 10:07 PM
As far as I can tell, parallel queues all events for all the functions (coroutines) that its running in parallel.