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

[Ask A Pro] Tables.....

Started by JustIan12, 30 June 2016 - 08:21 PM
JustIan12 #1
Posted 30 June 2016 - 10:21 PM
So I have just discovered the marvels of tables and well. I don't know how to read a table and use it? if that makes sense
so far I have.

sensor = peripheral.wrap("top")
pUnscramble = textutils.serialise(sensor.getPlayers())
write(pUnscramble)

It returns a table with a UUID and a name I want to only use the name and then compare it to a list of names using an if statement?

- Light
Lupus590 #2
Posted 30 June 2016 - 10:37 PM

for k, v = pairs(table) do
  print("key: "..k.." value: "..v)
end

run your table through this and see if you can figure it out
KingofGamesYami #3
Posted 30 June 2016 - 10:39 PM
It would help if you showed us the exact output, since different addons return differently formatted tables, and different versions can change this as well.

However, quick overview:


local mytbl = { [1] = "Hello", world = "World!" }
print( mytbl[ 1 ] ) --#prints "Hello"
print( mytbl.world ) --#prints "World!"

In some cases, a table may not explicitly show numerical indexes when serialized, because this is completely valid syntax:

local mytbl = {"a table", "of things"}
print( mytbl[ 1 ] ) --#prints "a table"
print( mytbl[ 2 ] ) --#prints "of things"

Finally, there's a nice trick for comparing something to a list of names, and that is to use a lookup table:

local tPlayerLookup = {
  ["KingofGamesYami"] = true,
  ["Justlan122"] = true,
}

print( "Enter a name: " )
if tPlayerLookup[ read() ] then
  print( "You're in the table!" )
else
  print( "You're not in the table :(/>" )
end
JustIan12 #4
Posted 30 June 2016 - 11:13 PM
thankx