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

While true do help!

Started by Wolf132, 11 September 2016 - 01:22 PM
Wolf132 #1
Posted 11 September 2016 - 03:22 PM
I am currently trying to make a program where I can talk to my friends wirelessly. I got the sending thing done but I need help with my receiver.
Here is my receiver code.

while true do
st = read()
X = true
m = peripheral.wrap("left")
rednet.open("right")
id, message = rednet.receive()
m.setTextScale(1)
m.setCursorPos(1,1)
m.write(message)
if st == "end" then
X = false
end
end

What I am trying to do is when you open the program it infinitely loops until the user types end. When I run the code and type end it just stops my computer making it impossible for me to type into it. Any help is appreciated.
ReBraLaCC #2
Posted 11 September 2016 - 05:18 PM

X = true
while X do
st = read()
m = peripheral.wrap("left")
rednet.open("right")
id, message = rednet.receive()
m.setTextScale(1)
m.setCursorPos(1,1)
m.write(message)
if st == "end" then
  X = false
end
end

Like that, or you just use break instead of X = false
Dog #3
Posted 11 September 2016 - 05:45 PM
I would recommend you wrap the peripheral, set your text scale, and open your rednet side outside of the loop - no reason to do it over and over again. I also recommend that you localize your variables - local variables are safer (because only the program using them can see them) and they are faster as well.

local m = peripheral.wrap("left")
m.setTextScale(1)
rednet.open("right")
while true do
  local st = read()
  local id, message = rednet.receive()
  m.setCursorPos(1,1)
  m.write(message)
  if st == "end" then
    break
  end
end

The other problem you are going to run into with your current implementation is that after you type something, the program will still wait to receive a rednet message after you've typed in "end" for example. Also, the program won't receive any messages while it's waiting for your input. I'd suggest using the parallel api so you can wait for rednet message and collect user input at the same time…

local m = peripheral.wrap("left")
m.setTextScale(1)
rednet.open("right")
local target = 52 --# the computer ID you will be sending to

local function getUserInput()
  while true do
    local st = read()
    if st == "end" then
      return --# if the user types 'end' then return from this loop and function
    else
      rednet.send(target, st) --# if the user didn't type 'end' then send the message to the target computer
    end
  end
end

local function receiveRednet()
  while true do
    local id, message = rednet.receive()
    m.setCursorPos(1,1)
    m.write(message)
  end
end

parallel.waitForAny(getUserInput, receiveRednet) --# this will allow both functions to operate and will exit if either of them returns