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

Background rednet.receive() or so.pullEvent()

Started by Hatchcatch020, 13 July 2015 - 06:47 PM
Hatchcatch020 #1
Posted 13 July 2015 - 08:47 PM
Hello, I know their is no true multitasking in computercraft but I thought that their must be a way to do something similar.

So my question is, how can I run a program which allows me to do one process (like running one function) Whilst I wait for a rednet response. One application of this I though out was having a turtle executing a program where it is digging or whatever until it receives a rednet message which could allow me to terminate the process remotely and have it execute another function. I thought this could also be useful for having a computer being able to run a shell or a program until it receives a rednet event making it do something else.

So I was wondering if anyone can help me out with running functions or programs almost simultaneously.
Edited on 13 July 2015 - 06:56 PM
Lupus590 #2
Posted 13 July 2015 - 08:59 PM
Look into the parallel API, if it doesn't do what you need then use it as a learning resource.
HPWebcamAble #3
Posted 13 July 2015 - 09:18 PM
You are correct, there isn't true multitasking, but you can get very close with coroutines


The parallel API (Like Lupus pointed out above) is what is known as a coroutine manager, and lets you run 2 or more functions 'simultaneously'

It counts on each one yielding (calling 'os.pullEvent()') in some way, at which point it starts running the next one.
flaghacker #4
Posted 13 July 2015 - 10:49 PM
Or you could use os.pullEvent to pull a rednet_message event instead of rednet.receive:


rednet.open ("left") --modem side

while true do
  event = {os.pullEvent ()}

  if event [1] == "rednet_message" then
    print ("reveived", event [3], "from", event [2], "with protocol", event [4])
  else
    --do other stuff
  end
end
Edited on 13 July 2015 - 08:50 PM
LewisTehMinerz #5
Posted 14 July 2015 - 04:15 PM
If you want, parallel api:


parallel.waitForAll(
function()
	--# os.pullEvent(...) or rednet.receive()
	... (other code)
end,
function()
	... (other code)
end
)

NOTE: You don't need to use waitForAll. You can use waitForAny. Also, if you use waitForAny, the parallel function will quit if a function errors (so nothing else that you put in parallel will run, waitForAll waits for all functions to quit/error), hence the name waitForAny. Also, put while true do around your code to make them run forever.
Edited on 14 July 2015 - 02:18 PM