--树形打印table
local print = print
local tconcat = table.concat
local tinsert = table.insert
local srep = string.rep
local type = type
local pairs = pairs
local tostring = tostring
local next = next
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
Lua table树状打印
于 2022-12-06 14:18:37 首次发布
本文介绍了一个使用Lua编写的函数,该函数可以将Table结构以树形的方式打印出来,便于开发者查看复杂的数据结构。通过递归遍历Table,并利用缓存机制避免无限循环,实现了清晰的层级展示。
967

被折叠的 条评论
为什么被折叠?



