PHP people know php print_r/var_export function, can be conveniently used to print arrays or export variables, LUA does not provide, in practical applications is often required similar functions.
Today, we encapsulate a simple function that implements a similar function for printing/exporting table:
--Dump.lua--[[dump Object @param mixed Obj@return string]]function debug.dump (obj) local getindent, Quotestr, Wrapkey, wrapval, dumpobj getindent = function (level) return String.rep ("\ T", level) end quotestr = function (str) str = string.gsub (str, "[%c\\\"] ", { ["\ t"] = "\\t", ["\ r"] = "\\r", ["\ n"] = "\\n", ["\"] = "\\\" ", ["\ \"] = "\\\\", }) return ' "'. Str.. ' ' end wrapkey = function (val) if Type (val) = = "Number" then return "[".. Val.. "]" ElseIf type (val) = = "string" then return "[".. Quotestr (val): "]" else Return "[".. ToString (val): "]" end end wrapval = function (val, Level) if Type (val) = = "Table" then return DumpObj (Val, level) ElseIf type (val ) = = "Number" then return val ElseIf Type (val) = = "string" Then return Quotestr (val) else return ToString (val) end end dumpobj = function (obj, level ) if Type (obj) ~= "table" then return Wrapval (obj) end level = level + 1 Local tokens = {} tokens[#tokens + 1] = "{" for-K, V in pairs (obj ) do tokens[#tokens + 1] = GetIndent (level): Wrapkey (k).. " = " .. Wrapval (V, level): "," End tokens[#tokens + 1] = GetIndent (LEVEL-1): "}" return Table.concat (tokens, "\ n") end Return dumpobj (obj, 0) end
Test code:
--Test.lualocal obj = {string1 = "hi! My name is Lixianlin ", string2 =" aa\tbb\rcc\ndd\\ee\ "ff", string3 = "a\\tb\\rc\\n\\\\ee\" ff ", int = 9527, flo at = 3.1415, bool = true, table = {1, 2, 3, {a = +, B = $, c = 23 ,},}, [88888] =, [9.7] = 22222,}print (debug.dump (obj)
Output Result:
{ ["string1"] = "hi! My name is Lixianlin ", [9.7] = 22222, ["table"] = { [1] = 1, [2] = 2, [3] = 3, [4] = { [" B "] = 22, ["a"] = 21, ["c"] = 23, }, }, ["float"] = 3.1415, ["int"] = 9527, ["string3"] = "a\\tb\\rc\\n\\\\ee\" ff ", [" bool "] = True, ["string2"] = "aa\tbb\rcc\ndd\\ee\" FF ", [88] = 88888,}
Function Features:
1. Theoretically supports infinite table nesting
2, formatted output, good readability
3. Output can be directly used in LUA code
4, function, UserData, thread type tostring output
5. When there are control characters in the string, there may be an impact (the code only handles \t,\r,\n, etc.)
Lua Print table (PHP-like Print_r/var_export)