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

Trouble Iterating through Table

Started by ozybrum, 28 July 2014 - 02:54 PM
ozybrum #1
Posted 28 July 2014 - 04:54 PM
Hey guys writing a networking program for my base and having what im sure is probably a small issue with this function.

This is the server code and is looking for a response from a client computer on the network. The message is received fine however for some reason the code wont iterate though the table properly (no error). The goal is to check whether or not the client responding is already in the table of clients or not. The signals and output work fine without the for loops but with them the printed text within them isn't shown at all not even the stuff in else.

Bit tired so it might just be a small oversight (only started learning lua 2 days ago).


function response() -- Wait for broadcast responses from the clients.
while true do
  id, message = rednet.receive()
  if message == "here!" then
   for k, v in pairs(clients) do
    for k, v in pairs(clients[k]) do
	 if v == id then
	  print("Computer ID: "..id.."already connected")
	 else
	  local i = 1
	  print("INFO: Computer ID: "..id.." connected!") -- Print this message only if the computer is not already in the system
	  clients[i] = {id, "connected"}
	  i = i + 1
	 end
    end
   end
  end
end
end

Cheers,

Ozy
KingofGamesYami #2
Posted 28 July 2014 - 05:24 PM
Part of the problem might be the fact that you use the variables k and v multiple times… The other part might be the fact that if a client isnt connected, you overwrite the first value in the table. Take your pick.

Just a little suggestion:

local clients = {}
function response()
 while true do
 local id, message = rednet.recieve()
 if message == "here!" then
  if clients[id] then
   print( "Computer ID: "..id.." already connected!" )
  else
   print( "Computer ID: "..id.." connected!" )
   clients[ id ] = true
  end
 end
end
ozybrum #3
Posted 29 July 2014 - 02:43 AM
You made a slight typo in your code that i've made several times before: 'recieve' has the 'e' before the 'i' but cheers mate much appreciated, still trying to learn what the best practices in lua are and yeah having the i = i + 1 where it is was a pretty silly oversight and I like the idea of using the id as the key and then boolean for the connection, learning heaps thanks again.