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

Selecting a random value from a table

Started by XMrPotatoX, 13 December 2013 - 04:54 PM
XMrPotatoX #1
Posted 13 December 2013 - 05:54 PM
So I have computers located around my central computer and I want them all to broadcast their ID numbers to the central computer which is supposed to choose one at random and send it a message. So far I can get the IDs to be stored in a table and I can choose an entry at random, but when it displays the chosen ID it displays it like this {["id"]=17}
The error I get is:

rednet:39: Expected number
because the variable A isn't a number

So how would I be able to pull out only the ID number?

Here's my code:

rednet.open("back")
IDs = {}

print("How many computers would you like to use?")
X = tonumber(read())
rednet.broadcast(os.computerID())
for a=1 X do
  cID, cMsg, cDis = rednet.receive()
  table.insert(IDs, {id=cID})
end

A = textutils.serialize(IDs[math.random(1, X)])
print(A)

rednet.send(A, "Go", true)

Thanks in advance for any help :D/>
gezepi #2
Posted 13 December 2013 - 06:45 PM
The line
table.insert(IDs, {id=cID})
inserts a table with one entry (["id"]) into the table IDs. You can get the ID out with
print(A.id)

Or the second way to fix it is to change the insert line to this:
table.insert(IDs, cID)
And get the ID out like this:
print(A)
XMrPotatoX #3
Posted 13 December 2013 - 07:05 PM
The line
table.insert(IDs, {id=cID})
inserts a table with one entry (["id"]) into the table IDs. You can get the ID out with
print(A.id)

THANK YOU! :D/> This worked perfectly, you've helped me more than you know :D/>