Jump to content




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

networking lua utility

4 replies to this topic

#1 Hatchcatch020

  • New Members
  • 2 posts
  • LocationUnited Kingdom

Posted 13 July 2015 - 07: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 by Hatchcatch020, 13 July 2015 - 07:56 PM.


#2 Lupus590

  • Members
  • 2,029 posts
  • LocationUK

Posted 13 July 2015 - 07:59 PM

Look into the parallel API, if it doesn't do what you need then use it as a learning resource.

#3 HPWebcamAble

  • Members
  • 933 posts
  • LocationWeb Development

Posted 13 July 2015 - 08: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.

#4 flaghacker

  • Members
  • 655 posts

Posted 13 July 2015 - 09: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 by flaghacker, 13 July 2015 - 09:50 PM.


#5 LewisTehMinerz

  • Members
  • 174 posts
  • LocationMinecraft in Minecraft in Minecraft in ComputerCraft... in Minecraft

Posted 14 July 2015 - 03: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 by LewisTehMinerz, 14 July 2015 - 03:18 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users