云风的个人空间 : 树型打印一个 table[LuaPrintR]

首页 :: 索引 :: 修订历史 :: 你好, 18.188.91.223
你的足迹: » 树型打印一个 table
这是一个旧版本的LuaPrintR于2009-05-03 00:52:40.
调试 lua 程序的时候往往想以树的形式打印出一个 table ,下面这个 print_r 函数可以满足要求。

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