Skip to content

Instantly share code, notes, and snippets.

@cuixin
Last active July 17, 2019 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuixin/f786e3e6e18f231f5a82115abc6b93de to your computer and use it in GitHub Desktop.
Save cuixin/f786e3e6e18f231f5a82115abc6b93de to your computer and use it in GitHub Desktop.
lua table.dump to dump a whole table to print_r.
local type = type
local tostring = tostring
local table = table
local table_insert = table.insert
local table_concat = table.concat
local pairs = pairs
return function(t, name, indent)
local table_list = {}
local function table_r(t, name, indent, full)
local id = not full and name
or type(name) ~= "number" and tostring(name) or '[' .. name .. ']'
local tag = indent .. id .. ' = '
local out = {} -- result
if type(t) == "table" then
if table_list[t] ~= nil then table_insert(out, tag .. '{} -- ' .. table_list[t] .. ' (self reference)')
else
table_list[t] = full and (full .. '.' .. id) or id
local _, is_nil_v = next(t)
if is_nil_v ~= nil then -- Table not empty
table_insert(out, tag .. '{')
for key, value in pairs(t) do
table_insert(out, table_r(value, key, indent .. '| ', table_list[t]))
end
table_insert(out, indent .. '}')
else table_insert(out, tag .. '{}')
end
end
else
local val = type(t) ~= "number" and type(t) ~= "boolean" and '"' .. tostring(t) .. '"' or tostring(t)
table_insert(out, tag .. val)
end
return table_concat(out, '\n')
end
return table_r(t, name or 'Value', indent or '')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment