树形打印table
function table.print (val)local function loop (val, keyType, _indent)_indent = _indent or 1keyType = keyType or "string"local res = ""local indentStr = " " -- 缩进空格local indent = string.rep(indentStr, _indent)local end_indent = string.rep(indentStr, _indent - 1)local putline = function (...)local arr = { res, ... }for i = 1, #arr doif type(arr[i]) ~= "string" then arr[i] = tostring(arr[i]) endendres = table.concat(arr)endif type(val) == "table" thenputline("{ ")if #val > 0 thenlocal index = 0local block = falsefor i = 1, #val dolocal n = val[i]if type(n) == "table" or type(n) == "function" thenblock = truebreakendendif block thenfor i = 1, #val dolocal n = val[i]index = index + 1if index == 1 then putline("\n") endputline(indent, loop(n, type(i), _indent + 1), "\n")if index == #val then putline(end_indent) endendelsefor i = 1, #val dolocal n = val[i]index = index + 1putline(loop(n, type(i), _indent + 1))endendelseputline("\n")for k, v in pairs(val) doputline(indent, k, " = ", loop(v, type(k), _indent + 1), "\n")endputline(end_indent)endputline("}, ")elseif type(val) == "string" thenval = string.gsub(val, "\a", "\\a") -- 响铃(BEL)val = string.gsub(val, "\b", "\\b") -- 退格(BS),将当前位置移到前一列val = string.gsub(val, "\f", "\\f") -- 换页(FF),将当前位置移到下页开头val = string.gsub(val, "\n", "\\n") -- 换行(LF),将当前位置移到下一行开头val = string.gsub(val, "\r", "\\r") -- 回车(CR),将当前位置移到本行开头val = string.gsub(val, "\t", "\\t") -- 水平指标(HT),(调用下一个TAB位置)val = string.gsub(val, "\v", "\\v") -- 垂直指标(VT)putline("\"", val, "\", ")elseif type(val) == "boolean" thenputline(val and "true, " or "false, ")elseif type(val) == "function" thenputline(tostring(val), ", ")elseif type(val) == "nil" thenputline("nil, ")elseputline(val, ", ")endreturn resendlocal res = loop(val)res = string.gsub(res, ",(%s*})", "%1")res = string.gsub(res, ",(%s*)$", "%1")res = string.gsub(res, "{%s+}", "{}")return resend
