標籤:lua debug.dump print_r var_export
會PHP的人都知道PHP中的print_r/var_export函數,可以方便的用於列印數組或匯出變數,Lua中沒有提供,實際應用中卻是很多時候需要類似的功能。
今天便封裝了個簡單函數,實作類別似功能,用來列印/匯出table:
-- dump.lua--[[dump對象@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.lualocal obj = { string1 = "Hi! My name is LiXianlin", string2 = "aa\tbb\rcc\ndd\\ee\"ff", string3 = "a\\tb\\rc\\n\\\\ee\"ff", 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)
輸出結果:
{ ["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,}
函數特點:
1、理論上支援無限級table嵌套
2、格式化輸出,可讀性好
3、輸出結果可直接用於lua代碼
4、function、userdata、thread類型tostring輸出
5、當字串中含有控制字元時,可能有影響(代碼中僅對\t,\r,\n等進行了處理)
Lua print table(類似PHP中的print_r/var_export)