代码如下:
function dump(o)
local t = {}
local _t = {}
local _n = {}
local space, deep = string.rep(' ', 2), 0
local type = _ENV.type
local function _ToString(o, _k)
if type(o) == ('number') then
table.insert(t, o)
elseif type(o) == ('string') then
table.insert(t, string.format('%q', o))
elseif type(o) == ('table') then
local mt = getmetatable(o)
if mt and mt.__tostring then
table.insert(t, tostring(o))
else
deep = deep + 2
table.insert(t, '{')
for k, v in pairs(o) do
if v == _G then
table.insert(t, string.format('\r\n%s%s\t=%s ;', string.rep(space, deep - 1), k, "_G"))
elseif v ~= package.loaded then
if tonumber(k) then
k = string.format('[%s]', k)
else
k = string.format('[\"%s\"]', k)
end
table.insert(t, string.format('\r\n%s%s\t= ', string.rep(space, deep - 1), k))
if v == nil then
table.insert(t, string.format('%s ;', "nil"))
elseif type(v) == ('table') then
if _t[tostring(v)] == nil then
_t[tostring(v)] = v
local _k = _k .. k
_t[tostring(v)] = _k
_ToString(v, _k)
else
table.insert(t, tostring(_t[tostring(v)]))
table.insert(t, ';')
end
else
_ToString(v, _k)
end
end
end
table.insert(t, string.format('\r\n%s}', string.rep(space, deep - 1)))
deep = deep - 2
end
else
table.insert(t, tostring(o))
end
table.insert(t, " ;")
return t
end
t = _ToString(o, '')
return table.concat(t)
end
使用示例:
-- 定义表数据
local t = {
"Apple", "Banana", "Pear",
["Vegetables"]={
"Tomato","Potato"
},
}
-- 输出表信息
print(dump(t))
转载请标注原作者和原文章链接
https://blog.youkuaiyun.com/qq_66458871/article/details/142577363