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

Modem best practice

Started by fileinster, 16 September 2014 - 10:05 PM
fileinster #1
Posted 17 September 2014 - 12:05 AM
I have a program that displays a lot of information on a monitor. Most of this information is local, but I have a few things that are pulled from remote computers via modem. Everything works but I have a strong suspicion I am not doing things the best way and there is room for improvement. I also don't want to wait for modem events as I have timers built in elsewhere and I would like my monitor to be able to update every second. The snippet of code I am talking about is below:


function getmodem()
  local event, modemSide, senderChannel, replyChannel, message, senderDistance = os.pullEvent("modem_message")
  if replyChannel == 1 then
   ScndPwr = message
  end
  if replyChannel == 2 then
   fsChk = message
  end
  local event, modemSide, senderChannel, replyChannel, message, senderDistance = os.pullEvent("modem_message")
  if replyChannel == 1 then
   ScndPwr = message
  end
  if replyChannel == 2 then
   fsChk = message
  end
end

So here you can see I am waiting for two modems to send to me. If my thinking is correct the whole script will pause until I receive two messages. It also looks somewhat unreliable to me as well.

Is there a better way to do what I am trying to achieve?


Thanks!
Bomb Bloke #2
Posted 17 September 2014 - 03:08 AM
Generally, if at a certain point in my code I want to do different things depending on which events I get, I'll make an event-listening loop along these lines:

while true do
	local myEvent = {os.pullEvent()}
	
	if myEvent[1] == "timer" then
		-- In this case, myEvent[2] will be the timer ID.
		
	elseif myEvent[1] == "modem_message" then
		-- In this case, myEvent[2] will be modemSide, myEvent[3] will be senderChannel, etc.
		
	end
end

You could also use the parallel API, but in this case I don't see the need.
Edited on 01 October 2014 - 02:00 AM
fileinster #3
Posted 01 October 2014 - 01:36 AM
Thanks, Bomb!

I used the parallel API; it fitted my needs perfectly!