Created
April 2, 2014 21:27
-
-
Save britzl/9943528 to your computer and use it in GitHub Desktop.
Example of how to override print and pretty-print tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- keep the original print() | |
local _print = print | |
local indentation = "" | |
--- Pretty print a value | |
-- If the value is a table it's content will be printed as well (recursively) | |
local function pretty_print(value) | |
local t = type(value) | |
if t ~= "table" then | |
_print(indentation .. value) | |
else | |
for name,data in pairs(value) do | |
if type(data) == "table" then | |
_print(indentation .. name .. " = {") | |
indentation = indentation .. "\t" | |
pretty_print(data) | |
indentation = indentation:sub(1,#indentation-1) | |
_print(indentation .. "}") | |
else | |
_print(indentation .. name .. " = " .. tostring(data)) | |
end | |
end | |
end | |
end | |
--- Improved print() function | |
-- If multiple arguments are passed they will be printed using the normal | |
-- print() function. | |
-- If a single argument is passed it will be pretty printed if it's a table | |
local function improved_print(...) | |
if select('#',...) > 1 then | |
_print(...) | |
else | |
pretty_print(select(1, ...)) | |
end | |
end | |
-- replace print() with improved print function that will pretty print tables | |
print = improved_print | |
local some_table = { | |
root = { | |
children = { | |
{ | |
tag = { | |
foo = "bar", | |
boo = "far", | |
} | |
}, | |
{ | |
tag = { | |
foo = "bar", | |
boo = "far", | |
"value" | |
} | |
} | |
} | |
} | |
} | |
print("aaa",123) | |
print("single") | |
print(some_table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment