-- 将table转换成字符串输出,值为nil的字段不会输出
-- @ tb : 待转换table @fmt : 是否格式化输出结果 @lv : 当前为table中第几层,不用管 @ tb_exist : 不用管
function tableToString (tb, fmt, lv, tb_exist)
if type(tb) ~= "table" then return false end
lv = lv or 1
tb_exist = tb_exist or {} -- 用来记录已解析过的table,防止相互引用导致死循环,暂不想实现
local space = "\t"
local new_line = "\n"
if fmt == nil or fmt == false then
space = ""
new_line = ""
end
local sort_tb = {}
local final_text = ""
local function keyToString(key)
if type(key) == "number" then
return "[ " .. key .. " ] = "
elseif type(key) == "string" then
return "['" .. key .. "'] = "
end
end
for k in pairs(tb) do
local tb_k = {}
tb_k.key = k
tb_k.value = tb[k]
tb_k.text = new_line
for s = 1, lv do -- 在前面添加 lv个空格
tb_k.text = tb_k.text .. space
end
if type(tb_k.value) == "function" then -- 或者不用这个,直接在else里面自动tostring成function
tb_k.text = (tb_k.text) .. keyToString(tb_k.key) .. "function()"
elseif type(tb_k.value) == "table" then
tb_k.text = (tb_k.text) .. keyToString (tb_k.key) .. tableToString(tb_k.value, fmt, lv + 1, tb_exist)
elseif type(tb_k.value) == "string" then
tb_k.text = (tb_k.text) .. keyToString(tb_k.key) .. "\"" .. tb_k.value .. "\""
elseif type(tb_k.value) == "number" then
tb_k.text = (tb_k.text) .. keyToString(tb_k.key) .. tostring(tb_k.value)
-- 在数字后加上16进制显示
-- tb_k.text = tbk.text .. string.format("\t\t\t0x%08x ", tb_k.value)
else --"number" 、 "boolean" 等
tb_k.text = (tb_k.text) .. keyToString(tb_k.key) .. tostring(tb_k.value)
end
table.insert(sort_tb, tb_k)
end
-- 排个序
table.sort(sort_tb, function(a, b) return type(a.key) < type(b.key) end)
for i = 1, #sort_tb do -- 连接当前table中的所有字符串
final_text = final_text .. (sort_tb[i].text)
if i < #sort_tb then final_text = final_text .. "," end
end
-- 添加后面的大括号
if lv == 1 then
final_text = "table = {" .. final_text .. new_line .. "}"
else
if #sort_tb > 0 then
final_text = final_text .. new_line
for l = 1, lv - 1 do
final_text = final_text .. space
end
end
final_text = "{" .. final_text .. "}"
end
return final_text
end
使用方法:
local test_tb = {
1,"text",function()end,true,nil,{},
a = 1,b = "text", c = function()end,d = true, e = nil,f = {"text",a = {nil}}
}
print(tableToString(test_tb,true))
效果图

image
print(tableToString(test_tb))
~~~

image