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

[Solved] Exit a function early

Started by Cyclonit, 09 July 2012 - 07:54 PM
Cyclonit #1
Posted 09 July 2012 - 09:54 PM
Hi,

I just wrote a small script for opening the first available rednet modem but somehow it does not work properly. This is the function:

function rednetOpen()

	local sides = {"right", "left", "back", "front", "top", "bottom"}

	for i, side in ipairs(sides) do
	  
		if (rednet.open(side)) then
			return true
		end

	end

	return false

end

Sadly this function returns false, even though it opened a rednet modem. It simply does not exit when it opened the first available modem. I tried finding answers regarding this issue using google but all of the functions I found did use return the same way I did.

Cyclonit
MysticT #2
Posted 09 July 2012 - 09:58 PM
rednet.open doesn't return any value, so the if will allways evaluate to false, even if there's a modem. It opens the side for use with modem or cable, doesn't matter what's on that side.
If you want to use only modems, you can detect them with the peripheral api:

local function rednetOpen()
  for _,s in ipairs(rs.getSides()) do
    if peripheral.isPresent(s) and peripheral.getType(s) == "modem" then
	  rednet.open(s)
	  return true
    end
  end
  return false
end
Cyclonit #3
Posted 09 July 2012 - 10:09 PM
Sheesh should have noticed that… thank you