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

Rednet message turns up nil

Started by margeobur, 18 June 2013 - 01:20 AM
margeobur #1
Posted 18 June 2013 - 03:20 AM
Hi. I'm making a program for mining turtles and a monitoring/commanding program to go with it.
In the functions that send commands to the turtle, a message is repetitively sent until the turtle sends back a message. If the message is the string "ok", then a message is printed on the computer and a monitor on top of the computer.

My trouble is that, although the initial message is getting through (the turtle does do what I want), the message coming back is just nil. -_-/>

Here is one of the functions that sends a command:

local function callTurtle()
Dualprint("Calling up turtle...")
while true do
  rednet.send(turtleID, "ComeUp")
  local senderID, message = rednet.receive(0.7)
  if senderID then
   break
  end
end
print("message: ".. message)
if senderID then
  if senderID ~= turtleID then
   print("Comunications were interrupted.")
   return false
  end
  if message == "ok" then
   Dualprint("Turtle is coming up")
  end
end
end

and here is the function in the turtle program that checks if a command is being sent:

local function receive()
local sender, message, distance = rednet.receive(2)
if not sender then
  return false
end
if sender ~= monitorID then
  rednet.send(sender, "You are not my monitor!")
end
if message == "CheckStatus" then
  local Status = getStatus()
  print("Serialising and sending status")
  local sStatus = textutils.serialize(Status)
  rednet.send(monitorID, sStatus)
  return true
elseif message == "Empty" then
  rednet.send(monitorID, "ok")
  return 4
elseif message == "Refuel" then
  rednet.send(monitorID, "ok")
  return 3
elseif message == "ComeUp" then
  rednet.send(monitorID, "ok")
  return 5
else
  rednet.send(monitorID, "Unknown command")
  return false
end
return true
end

I will probably end up changing the command-sending functions a little anyway, but if someone could help it would be greatly apreciated.
Bomb Bloke #2
Posted 18 June 2013 - 08:09 AM
In the server code, you're declaring "senderID" and "message" as being local to the while loop they're defined in. This leads to them being discarded as soon as you break out of that loop.

If you want them local to the function, pre-declare them as such before that while loop starts. Eg:

local senderID, message = 0, ""
while true do
  rednet.send(turtleID, "ComeUp")
  senderID, message = rednet.receive(0.7)
  .
  .
  .

If you're interested, the parallel API offers a nice and easy way to have the turtle process rednet stuff while doing other things.
margeobur #3
Posted 18 June 2013 - 04:21 PM
Ohhh, does scoping apply to loops as well? *derp* Right, thanks. :)/> Yeah, I've tried using the parallel api a little but it did some weird things, I might go back to it soon and see.