PDA

View Full Version : Printing the contents of a table



SpudmanWP
January 18th, 2011, 22:30
I was stuck trying to populate dieList from a table of values and was trying to validate the dieList table after the fact. I found and adapted a function online that will dive through every level (even sub tables) of a table and print the results to the console. Here are the steps:

1. Add these three lines where you want to print the table.
dPrtTmp = ""
table_print(name_of_table_goes_here)
print("Dumping Table: \r\n" .. dPrtTmp)


2. Add this function to your code.
function table_print (tt, indent, done)
done = done or {}
indent = indent or 0
if type(tt) == "table" then
for key, value in pairs (tt) do
dPrtTmp = dPrtTmp .. (string.rep (" ", indent)) -- indent it
if type (value) == "table" and not done [value] then
done [value] = true
dPrtTmp = dPrtTmp .. (string.format("[%s] => table\n", tostring (key)));
dPrtTmp = dPrtTmp .. (string.rep (" ", indent+4)) -- indent it
dPrtTmp = dPrtTmp .. ("(\n");
table_print (value, indent + 7, done)
dPrtTmp = dPrtTmp .. (string.rep (" ", indent+4)) -- indent it
dPrtTmp = dPrtTmp .. (")\n");
else
dPrtTmp = dPrtTmp .. (string.format("[%s] => %s\n",
tostring (key), tostring(value)))
end
end
else
dPrtTmp = dPrtTmp .. (tt .. "\n")
end
end

3. Make sure the console is open and copy it to the clipboard, open a word processor, and past the results.

Here is a sample of what it looks like in the console:
Script Notice: Dumping Table: [1] => table | (| [result] => 3| [type] => d6| )|[2] => table| (| [result] => 3| [type] => d6| )|[3] => table| (| [result] => 1| [type] => d6| )

When you copy it to a word processor, it looks like this.
Script Notice: Dumping Table:
[1] => table
(
[result] => 3
[type] => d6
)
[2] => table
(
[result] => 3
[type] => d6
)
[3] => table
(
[result] => 1
[type] => d6
)

I hope you find this as useful as I did.

Bidmaron
January 18th, 2011, 22:51
Hey, Obe and/or Drahkar, can we get this put onto the fgWiki? This looks very useful (maybe it should be in Moon's debugging kit?), and I'm sure it will fade into the quagmire of forum oblivion.

Moon Wizard
January 19th, 2011, 07:36
I already have something in my debugging extension in progress which is similar.

Cheers,
JPG

drahkar
January 19th, 2011, 07:40
If Spud doesn't have a problem I can post this up on FGWiki. It would at least give a solid tool till moon finishes with the debugging tools. :)

Bidmaron
January 19th, 2011, 12:58
Moon, will your debugging extension offer a simple 'dialog box' kind of window where you can tell the user something and get a yes/no ok/cancel kind of answer without binding to the database?

SpudmanWP
January 19th, 2011, 16:53
Do with it as you please.. that's why I posted it :)