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 }
让我们像月光一样