Luadumptable (like print_rvar_export in PHP) will know the print_rvar_export function in PHP, which can be conveniently used to print arrays or export variables, which is not provided in Lua, in actual applications, the function of class & #20284; is often required. Today, a simple function is encapsulated to implement the class & #20284; function to print and export the table: -- dump. lua Lua dump table (similar to print_r/var_export in PHP)
Anyone in PHP will know the print_r/var_export function in PHP, which can be easily used to print arrays or export Variables. This function is not provided in Lua, but is often required in practical applications.
Today, a simple function is encapsulated to implement similar functions to Print/export tables:
-- 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) return '"'.. string. gsub (str ,'"','\\"').. '"'end wrapKey = function (val) if type (val) =" number "then return "[".. val .. "]" elseif type (val) = "string" then return "[".. q UoteStr (val ).. "]" else return "[".. tostring (val ).. "]" 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 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 = { string = "hello", int = 9527, float = 3.1415, bool = true, table = { 1, 2, 3, { a = 21, b = 22, c = 23, }, }, [88] = 88888, [9.7] = 22222,}print(debug.dump(obj))
Output result:
{ ["float"] = 3.1415, [9.7] = 22222, ["string"] = "hello", [88] = 88888, ["bool"] = true, ["int"] = 9527, ["table"] = { [1] = 1, [2] = 2, [3] = 3, [4] = { ["b"] = 22, ["a"] = 21, ["c"] = 23, }, },}
Function features:
1. Theoretically supporting infinite table nesting
2. format the output and make it readable.
3. the output result can be directly used for lua code.
4. function, userdata, thread type tostring output