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

[Lua][Question] Using parallel.waitForAny()

Started by AstronautG117, 11 December 2012 - 09:11 AM
AstronautG117 #1
Posted 11 December 2012 - 10:11 AM
Hey guys. I'm trying to write a function that will either wait for a rednet message or for user input, but the content of the message is important. Is there any way for a parallel function to return whichever value that the function finishes first returns?

function getUserInput(cartPresent)

  local floor

  if cartPresent then
	print "Type floor number:"
	local input = read()
	if input == "1" then
	  floor = 1
	end
	if input == "2" then
	  floor = 2
	end
  else
	print "Press enter to call cart."
	read()
	floor = 0
  end

  return floor

end

function getRednetMessage()

  local floor
  local recieved = false

  repeat
	event, id, text = os.pullEvent()
	if event == "rednet_message" then
	  floor = text
	  recieved = true
	end
  until recieved

  return floor

end

rednet.open("back")

rs.setOutput("right", true)

local floor = 0

while true do

  if floor == 0 then
	if floor == 1 then
	  rednet.send(0, "on")
	end
	if floor == 2 then
	  rednet.send(1, "on")
	end
	rs.setOutput("right", true)
	sleep(3)
	rs.setOutput("right", false)
  end

end

This in particular is what I need to happen:
parallel.waitForAny((floor = getUserInput(true)), (floor = getRednetMessage))
Kingdaro #2
Posted 11 December 2012 - 10:16 AM
You could probably just set some variables, and then have functions set those variables.

local floor
parallel.waitForAny(
  function()
    floor = getUserInput(true)
  end,
  function()
    floor = getRednetMessage()
  end
)
AstronautG117 #3
Posted 11 December 2012 - 10:48 AM
Ah, I'll see if that works, if so, it's exactly what I'm looking for, thanks.

Edit: It worked wonderfully, thanks.