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

Turtles Waiting For Commads

Started by bigbaddevil6, 08 August 2013 - 08:33 PM
bigbaddevil6 #1
Posted 08 August 2013 - 10:33 PM
I have made multiple things that involve sending wireless commands. I was wondering the best way to make a computer wait for a message that is sent once and will keep executing untill another message is sent. Then main reason is I don't want the master computer to need loops to send the command to the turtles only the turtles will use loops.
Bubba #2
Posted 08 August 2013 - 10:56 PM
Well it somewhat depends on your situation, but the best way to go about this would probably be to use the parallel API. You can check it out on the wiki here, but it is essentially just a way to multi-task if given several functions.

So I would make one function that monitors the rednet messages, and another function that executes the operations based on a boolean value set by the monitor.
Example:

local shouldExecute = false
local function monitor()
  while true do
	--# You can probably code this. If not I'll be happy to help you out

	shouldExecute = true
	--# Somewhere along the line, set the execute value to true or false
  end
end

local function execute()
  while true do
	if shouldExecute then
	  --# Do the stuff
	end
  end
end

parallel.waitForAll(monitor, execute)

Another possibility is to use timers. This is probably considerably easier, but you may be limited by what you can do.

Timers would be useful if you want to do things with redstone, or something that always runs in set increments.

An example of using timers to run a redstone pulser:

local function execute()
  -- # Do whatever you need to here
end
local shouldRun = false --# We'll use this to keep track of whether we should execute code or not
local timer = false --# We haven't instantiated the timer yet, but eventually we'll keep the timer ID in this variable
while true do
  local event, arg1, arg2, arg3, arg4 = os.pullEvent() --# Wait for stuff to happen
  if event == "timer" and arg1 == timer and shouldRun then --# So if the timer has the correct id, and we are supposed to execute the code
	timer = os.startTimer(1) --# 1 would be the interval you want to repeat at -- # Restart the timer and execute the code
	execute()
  elseif event == "modem_message" then --# Otherwise if we have a message sent to us
	shouldRun = not shouldRun --# Invert the shouldRun value. So if shouldRun is true, it will turn to false. If it is false, turn it to true.
  end
end