lua 打印一个table的实现

Posted niyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lua 打印一个table的实现相关的知识,希望对你有一定的参考价值。

print("-------------Test-----------------")

local tb = {}

function printProperties(t, csp)
    local parentOffset = csp or ""
    local propertyOffset = parentOffset .. "\\t"
    local str = ""
    str = str .. "{" .. "\\n"
    for k, v in pairs(t) do
         if type(v)=="table" then
             str = str .. propertyOffset.. k .. " = " .. printProperties(v, propertyOffset) .. ",\\n"
         else
             str = str .. propertyOffset.. k .. " = ‘" .. v .. "‘,\\n"
         end
    end
    str = string.sub(str, 1, string.len(str) - string.len(",\\n")) .. "\\n"
    str = str .. parentOffset .. "}"
    return str
end

function printTb( tb )  
  print(printProperties(tb))
end

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

printTb(myTable)

  效果:

技术分享图片

 

以上是关于lua 打印一个table的实现的主要内容,如果未能解决你的问题,请参考以下文章

lua 打印table

Lua笔记——4.环境Environment

打印lua中全局变量的一段代码

lua 的 “传值” 与 “传引用”(亦称 “传址”)

Lua用table实现各种数据结构-队列

Lua遍历table