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

[Lua][Help] Printing entire tables

Started by soccer16x, 19 February 2013 - 09:07 AM
soccer16x #1
Posted 19 February 2013 - 10:07 AM
So basically i just forget how to print out entire tables, like for miscperipherals i want to print out m.list() but its a table and i forget what to do to print that out, can anyone help?
JokerRH #2
Posted 19 February 2013 - 10:39 AM
You could use

    textutils.serialize()
which will return a string, or you can use

    for index, param in pairs(table) do
        print(index..": "..tostring(param))
    end

(obviously the textutils method is the easiest way…:)/> )
Lyqyd #3
Posted 19 February 2013 - 10:40 AM

for k, v in pairs(tableVariable) do
  print(tostring(k)..": "..tostring(v))
end

Edit to respond to the post above which was submitted while I was writing my reply: You need to tostring both the key and the value, because boolean true and false are acceptable table keys. Table serialization does not also print the table, and is not designed to be pleasant for humans to read.
JokerRH #4
Posted 19 February 2013 - 10:51 AM
@Lyqyd: It may not be designed to be read, but it is really helpfull for
Debugging your code (means for temporary use)
Kingdaro #5
Posted 19 February 2013 - 10:53 AM
Doesn't work very well for tables within tables, though. Here's a nice recursive solution:

function dump(t, level)
	level = level or 0
	for i,v in pairs(t) do
		io.write(string.rep('  ', level))
		io.write(i..': ')
		if type(v) == 'table' then
			print ''
			dump(v, level + 1)
		else
			print(tostring(v))
		end
	end
end

local thing = {
	a_table = {
		another_table = {
			some_value = 'a string'
		}
	}
}

dump(thing)
soccer16x #6
Posted 19 February 2013 - 11:11 AM

for k, v in pairs(tableVariable) do
  print(tostring(k)..": "..tostring(v))
end

Edit to respond to the post above which was submitted while I was writing my reply: You need to tostring both the key and the value, because boolean true and false are acceptable table keys. Table serialization does not also print the table, and is not designed to be pleasant for humans to read.

Thanks, that's what i was looking for, I just had forgotten how to do this, and couldnt seem to find it on google