转自:
http://blog.codingnow.com/cloud/LuaPrintR
调试 lua 程序的时候往往想以树的形式打印出一个 table ,下面这个 print_r 函数可以满足要求。
1 local print = print
2 local tconcat = table.concat
3 local tinsert = table.insert
4 local srep = string.rep
5 local type = type
6 local pairs = pairs
7 local tostring = tostring
8 local next = next
9
10 function print_r(root)
11 local cache = { [root] = "." }
12 local function _dump(t,space,name)
13 local temp = {}
14 for k,v in pairs(t) do
15 local key = tostring(k)
16 if cache[v] then
17 tinsert(temp,"+" .. key .. " {" .. cache[v].."}")
18 elseif type(v) == "table" then
19 local new_key = name .. "." .. key
20 cache[v] = new_key
21 tinsert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. srep(" ",#key),new_key))
22 else
23 tinsert(temp,"+" .. key .. " [" .. tostring(v).."]")
24 end
25 end
26 return tconcat(temp,"\n"..space)
27 end
28 print(_dump(root, "",""))
29 end
1 a = {}
2
3 a.a = {
4 hello = {
5 alpha = 1 ,
6 beta = 2,
7 },
8 world = {
9 foo = "ooxx",
10 bar = "haha",
11 root = a,
12 },
13 }
14 a.b = {
15 test = a.a
16 }
17 a.c = a.a.hello
18
19 print_r(a)
输出:
1 +a+hello+alpha [1]
2 | | +beta [2]
3 | +world+root {.}
4 | +bar [haha]
5 | +foo [ooxx]
6 +c {.a.hello}
7 +b+test {.a}
posted on 2013-01-24 14:19
风起浮尘 阅读(102)
评论(0) 编辑 收藏 引用 所属分类:
lua