首页 > 其他 > 详细

Lua完美打印一个Table的方案

时间:2015-01-17 12:34:21      阅读:333      评论:0      收藏:0      [点我收藏+]
function print_r ( t )  
    local print_r_cache={}
    local function sub_print_r(t,indent)
        if (print_r_cache[tostring(t)]) then
            print(indent.."*"..tostring(t))
        else
            print_r_cache[tostring(t)]=true
            if (type(t)=="table") then
                for pos,val in pairs(t) do
                    if (type(val)=="table") then
                        print(indent.."["..pos.."] => "..tostring(t).." {")
                        sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
                        print(indent..string.rep(" ",string.len(pos)+6).."}")
                    elseif (type(val)=="string") then
                        print(indent.."["..pos..] => "..val..")
                    else
                        print(indent.."["..pos.."] => "..tostring(val))
                    end
                end
            else
                print(indent..tostring(t))
            end
        end
    end
    if (type(t)=="table") then
        print(tostring(t).." {")
        sub_print_r(t,"  ")
        print("}")
    else
        sub_print_r(t,"  ")
    end
    print()
end

print_r函数可以完整的打印table,并且可以清晰的打印table中嵌套table的内容。对于调试和检查程序都有很大的好处。

另外,直接使用print_r不太符合直觉,可以把函数放如table的名字空间里,如下:

table.print = print_r

这样就可以自然的使用这个函数:

table.print( myTable )

打印的结果,类似下面内容:

local myTable = {
    firstName = "Fred",
    lastName = "Bob",
    phoneNumber = "(555) 555-1212",
    age = 30,
    favoriteSports = { "Baseball", "Hockey", "Soccer" },
    favoriteTeams  = { "Cowboys", "Panthers", "Reds" }
}

table.print_r(myTable)
table: 0x7fa832d012e0 {
  [firstName] => "Fred"
  [favoriteSports] => table: 0x7fa832d012e0 {
                        [1] => "Baseball"
                        [2] => "Hockey"
                        [3] => "Soccer"
                      }
  [phoneNumber] => "(555) 555-1212"
  [favoriteTeams] => table: 0x7fa832d012e0 {
                       [1] => "Cowboys"
                       [2] => "Panthers"
                       [3] => "Reds"
                     }
  [lastName] => "Bob"
  [age] => 30
}

Lua完美打印一个Table的方案

原文:http://www.cnblogs.com/leezj/p/4230271.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!