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

print the content of nested tables

Started by agowa338, 06 October 2015 - 07:19 PM
agowa338 #1
Posted 06 October 2015 - 09:19 PM
How can i print the content of a nested table without knowing the indexes and eventual nil entries in between?
If I'm not wrong in earlier versions it was possible to just "print(table())" and get a representation of the table.
But if I do that I'm only getting "table: 1f7da2b4".

So I looked around the web and it was suggested to use table.concat.
In lua terminal i get "lua:1: bad argument: string expected, got table) (Command: "table.concat(p.getAllStacks()" )

This didn't work, so I wrote this code:

p = peripheral.wrap("right")
list = p.getAllStacks()
for i, v in ipairs(list) do
    for a, b in ipairs(v) do
	    write(a)
	    write("	    ")
	    write(B)/>
    end
end
But it doesn't output anything (not even an error).


So how would I do this?
TYKUHN2 #2
Posted 06 October 2015 - 09:47 PM
print(textutils.serialize(table)) though I don't know if nested tables work. I assume so.
agowa338 #3
Posted 06 October 2015 - 10:08 PM
This only works if the Inventory in question is empty, if there is anything in I get the error message "Cannot serialize type function"
TYKUHN2 #4
Posted 06 October 2015 - 10:11 PM
Then table isn't a table, it's a function.
Try print(textutils.serialize(table()))
Notice I am calling table to see if it returns a table.
(I am worried it may be an iterator though so it may change)
valithor #5
Posted 06 October 2015 - 10:14 PM
Then table isn't a table, it's a function.
Try print(textutils.serialize(table()))
Notice I am calling table to see if it returns a table.
(I am worried it may be an iterator though so it may change)

If a table contains a function, then you can not serialize it using textutils.serialize.

Another way:


function exploreTable(tbl,prefix)
  prefix = prefix or ""
  for k,v in pairs(tbl) do
	if type(v) == "table" then
	  exploreTable(v,prefix.."  ")
	elseif type(v) == "function" then
	  print(prefix.."key: "..k.." function")
	else
	  print(prefix.."key: "..k.." value: "..v)
  end
end

edit:

edited code to make it to where you can visually see the nested tables.
Edited on 06 October 2015 - 08:19 PM