Lua prints an implementation of a table

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

local tb = {}

function printTb( tb )  
  local printFunc
  printFunc = function (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 .. " = " .. printFunc(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
  print(printFunc(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)

  running result:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325233264&siteId=291194637