目标table:
local a =
{
{
"a11",
"a12",
"a13"
},
{
"b21",
"b22",
"b23"
},
{
"c31",
"c32",
"c33",
ccc = {"cccc"},
cpt = {"uuuuu"}
},
{
"d12",
"d13",
d41 = {123},
d42 =
{
moo={456}
}
}
}
函数部分:
local u = 1
local i = 0 ---distance flag
local pp = 0
local cache = {}
local location_cache
local function print_table(arr,flag,distance)
pp = 0
u = u+1
if flag == 1 then
cache[tostring(arr)] = arr
for e in pairs(cache) do
print(tostring(e))
end
end
if u > flag then
u=u-1
return
end
if type(arr) == "table" then
for loc,value in pairs(arr) do
if type(value) == "table" then
i = i+1
if u == flag then
print(distance.." "..loc)
else
print(distance.." "..loc.." = ".." { ")
if pp == 0 then
location_cache = distance..string.rep(" ",9)
pp = pp+1
end
end
print_table(value,flag,string.rep(" ",string.len(loc)+u*6))
else
print(distance.." "..tostring(value))
end
end
i = 0
else
print(arr)
end
u = u-1
if #tostring(location_cache) > 0 and u ~= 1 then
print(location_cache.."}")
location_cache = " "
end
end
function table_print(arr,flag)
print_table(arr,flag,"")
end
table_print(a,1)
总结:函数包含2个参数,一个是传入的table,一个是需要打印的深度,这个打印table的递归不难实现,比较坑的地方是打印不同的深度,这一点需要注意,要设置不同的标记符号,每次进入到函数,深度加一,每完整的执行完一次,返回到上一个递归函数时,深度减一,这样可以时刻检查到当前的深度。
执行上面的代码,结果输出如图: