Skip to content

Instantly share code, notes, and snippets.

@rangercyh
Last active November 5, 2021 07:39
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save rangercyh/5814003 to your computer and use it in GitHub Desktop.
Save rangercyh/5814003 to your computer and use it in GitHub Desktop.
按照lua的table格式进行缩进打印lua的table,目前还不支持key为table,因为是自己还没想好,如果key是table的时候怎么打印出来比较优美
function print_lua_table (lua_table, indent)
indent = indent or 0
for k, v in pairs(lua_table) do
if type(k) == "string" then
k = string.format("%q", k)
end
local szSuffix = ""
if type(v) == "table" then
szSuffix = "{"
end
local szPrefix = string.rep(" ", indent)
formatting = szPrefix.."["..k.."]".." = "..szSuffix
if type(v) == "table" then
print(formatting)
print_lua_table(v, indent + 1)
print(szPrefix.."},")
else
local szValue = ""
if type(v) == "string" then
szValue = string.format("%q", v)
else
szValue = tostring(v)
end
print(formatting..szValue..",")
end
end
end
@zhao-jin
Copy link

zhao-jin commented Jun 6, 2014

very good

@zk4
Copy link

zk4 commented Jun 10, 2014

not very good. can`t print recursive table. like _G

@zk4
Copy link

zk4 commented Jun 10, 2014

better use this by feng yun

function print_r(root)
    local cache = {  [root] = "." }
    local function _dump(t,space,name)
        local temp = {}
        for k,v in pairs(t) do
            local key = tostring(k)
            if cache[v] then
                tinsert(temp,"+" .. key .. " {" .. cache[v].."}")
            elseif type(v) == "table" then
                local new_key = name .. "." .. key
                cache[v] = new_key
                tinsert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. srep(" ",#key),new_key))
            else
                tinsert(temp,"+" .. key .. " [" .. tostring(v).."]")
            end
        end
        return tconcat(temp,"\n"..space)
    end
    print(_dump(root, "",""))
end

@rangercyh
Copy link
Author

in fact that, I wrote these code not for recusive table, I have no idea how to display a recusive table elegantly as well as if the key is a table.however,thanks:)

@wo4li2wang
Copy link

666

@rangercyh
Copy link
Author

you can just use 'luarocks install luatabledump' to install the model. https://luarocks.org/modules/rangercyh/luatabledump

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment