Lua完美打印一個Table的方案


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
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM