树型打印一个 table
php 中有个 print_r
函数,可以递归打印一张表。很多 php 程序员喜欢用这个去调试程序。
我想,所有写过一定代码量的 lua 程序员都会写一个类似的东西放着备用吧。这两天调试 lua 程序的时候,发现以前做的简陋的 print_r
不够好用。对于复杂的 table 打印出来一大篇很不直观。结果就放下手头的工作,花了整整一个小时,写了下面几十行代码。把 table 输出成树结构。
比如:
a = {} a.a = { hello = { alpha = 1 , beta = 2, }, world = { foo = "ooxx", bar = "haha", root = a, }, } a.b = { test = a.a } a.c = a.a.hello print_r(a)
可以输出成:
+a+hello+alpha [1] | | +beta [2] | +world+root {.} | +bar [haha] | +foo [ooxx] +c {.a.hello} +b+test {.a}
代码参考这里:
其实实现的细节需要注意的就两个地方:一个是考虑循环引用的问题。(一般用 table 模拟树结构都会记录一个 parent 节点的引用,这样就造成了循环引用)
一个是表格线的处理,对最后一个子节点需要特殊处理。
这段代码的输出风格不算美观,至少不如那些显示文件目录结构的命令行工具。不过我觉得是够用就成,另外需要尽量紧凑,不浪费空间。需要更美观的同学,其实也可以很容易的对其改进。
Comments
用递归实现的table的树形打印,基本上和原table形式一样。。
http://blog.csdn.net/laozitianxia/article/details/18733987
ps:最近在扒风云的blog看,刚进入游戏行业,还要多向大牛学习啊。。
Posted by: jason | (9) January 27, 2014 06:17 PM
如果key是table呢,会打印key的地址吧?
Posted by: katy | (8) October 29, 2012 03:18 PM
呵呵,变量一长,看这个树的是很很累,就少许修改了下:
function print_r(sth)
if type(sth) ~= "table" then
print(sth)
return
end
local space, deep = string.rep(' ', 4), 0
local function _dump(t)
local temp = {}
for k,v in pairs(t) do
local key = tostring(k)
if type(v) == "table" then
deep = deep + 2
print(string.format("%s[%s] => Table\n%s(",
string.rep(space, deep - 1),
key,
string.rep(space, deep)
)
) --print.
_dump(v)
print(string.format("%s)",string.rep(space, deep)))
deep = deep - 2
else
print(string.format("%s[%s] => %s",
string.rep(space, deep + 1),
key,
v
)
) --print.
end
end
end
print(string.format("Table\n("))
_dump(sth)
print(string.format(")"))
end
Posted by: alacner | (7) June 10, 2009 03:59 PM
用 PHP 时间不短了,竟然没注意还有 print_r 这个函数,真是惭愧啊。
Posted by: 辰玉 | (6) May 4, 2009 09:14 PM
to mm:
本人精通php,依然没人要!!
我要。。。发简历给我
Posted by: sunway | (5) May 4, 2009 09:19 AM
不知道有没有人需要暑期的兼职学生啊
Posted by: holight | (4) May 3, 2009 09:53 PM
本人精通php,依然没人要!!
Posted by: mm | (3) May 3, 2009 04:50 PM
php我都是用var_dump(),因为可以打印出变量的类型。
Posted by: xLight | (2) May 3, 2009 04:02 PM
第一,嘿嘿
Posted by: sky618 | (1) May 3, 2009 04:02 PM