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

dumpvar function (think print_r() from php)

Started by Elsys656, 11 March 2015 - 06:49 PM
Elsys656 #1
Posted 11 March 2015 - 07:49 PM
I DID NOT write this I cannot recall exactly where I found it but I've used it like crazy lately and it's super useful just like print_r for debugging

just call print(dumpvar(table))
or you can also use it to write a table to file
Spoiler

function dumpvar(data)
    -- cache of tables already printed, to avoid infinite recursive loops
    local tablecache = {}
    local buffer = ""
    local padder = "    "

    local function _dumpvar(d, depth)
	    local t = type(d)
	    local str = tostring(d)
	    if (t == "table") then
		    if (tablecache[str]) then
			    -- table already dumped before, so we dont
			    -- dump it again, just mention it
			    buffer = buffer.."<"..str..">\n"
		    else
			    tablecache[str] = (tablecache[str] or 0) + 1
			    buffer = buffer.."("..str..") {\n"
			    for k, v in pairs(d) do
				    buffer = buffer..string.rep(padder, depth+1).."["..k.."] => "
				    _dumpvar(v, depth+1)
			    end
			    buffer = buffer..string.rep(padder, depth).."}\n"
		    end
	    elseif (t == "number") then
		    buffer = buffer.."("..t..") "..str.."\n"
	    else
		    buffer = buffer.."("..t..") \""..str.."\"\n"
	    end
    end
    _dumpvar(data, 0)
    return buffer
end
oeed #2
Posted 11 March 2015 - 08:43 PM
I can imagine this being quite neat.

The only thing I can see is that it won't print out an entire table in full twice. I can understand that being useful, but maybe check if there are changes to the table, and if it's identical then don't print it, but I'd want to be able to see any changes.
GopherAtl #3
Posted 11 March 2015 - 08:52 PM
I can imagine this being quite neat.

The only thing I can see is that it won't print out an entire table in full twice. I can understand that being useful, but maybe check if there are changes to the table, and if it's identical then don't print it, but I'd want to be able to see any changes.

unless I misread it, it's only tables that appear twice within a given tree structure that get displayed once, so that is not actually a problem, as the table won't be modified during the call to dumpvar()