--[[
print_dump是一个用于调试输出数据的函数,能够打印出nil,boolean,number,string,table类型的数据,以及table类型值的元表
参数data表示要输出的数据
参数showMetatable表示是否要输出元表
参数lastCount用于格式控制,用户请勿使用该变量
]]
function print_dump(data, showMetatable, lastCount)
if type(data) ~= "table" then
--Value
if type(data) == "string" then
io.write("\"", data, "\"")
else
io.write(tostring(data))
end
else
--Format
local count = lastCount or 0
count = count + 1
io.write("{\n")
--Metatable
if showMetatable then
for i = 1,count do
io.write("\t")
end
local mt = getmetatable(data)
io.write("\"__metatable\" = ")
print_dump(mt, showMetatable, count) -- 如果不想看到元表的元表,可将showMetatable处填nil
io.write(",\n") --如果不想在元表后加逗号,可以删除这里的逗号
end
--Key
for key,value in pairs(data) do
for i = 1,count do
io.write("\t")
end
if type(key) == "string" then
io.write("\"", key, "\" = ")
elseif type(key) == "number" then
io.write("[", key, "] = ")
else
io.write(tostring(key))
end
print_dump(value, showMetatable, count) -- 如果不想看到子table的元表,可将showMetatable处填nil
io.write(",\n") --如果不想在table的每一个item后加逗号,可以删除这里的逗号
end
--Format
for i = 1,lastCount or 0 do
io.write("\t")
end
io.write("}")
end
--Format
if not lastCount then
io.write("\n")
end
end
--->字符串分割
---按照sign将string分割为table
function string:split(sign)
local tab = {}
self:gsub('[^' .. sign .. ']+', function(f)
table.insert(tab, f)
end)
return tab
end
--->删除字符串空格
function string:trim()
return self:gsub('%s', '')
end
--->万能连接
---搭配万能print及万能toast使用
function connectContent(...)
local content = { ... }
local function tabToStr(t)
local str = {}
local function tab(_t, num)
num = num + 1
for k, v in pairs(_t) do
local value = tostring(v)
local _type = type(v)
if _type == "table" and k ~= _G and not v.package then
if not next(v) then
str[#str + 1] = num == 0 and '' or ('\t'):rep(num) .. '[' .. tostring(k) .. '](table) = {}\r'
else
str[#str + 1] = num == 0 and '' or ('\t'):rep(num) .. '[' .. tostring(k) .. '](table) = {\r'
tab(v, num)
str[#str + 1] = num == 0 and '' or ('\t'):rep(num) .. '}\r'
end
else
if _type == "function" then
value = value:split(': ')[2]
end
str[#str + 1] = num == 0 and '' or ('\t'):rep(num) .. '[' .. tostring(k) .. '](' .. _type .. ') = ' .. value .. '\r'
end
end
end
if next(t) then
str[#str + 1] = '\r◇ ' .. tostring(t):split(': ')[2] .. '(table) = {\r'
tab(t, 0)
str[#str + 1] = '}\r'
else
str[#str + 1] = '◇ ' .. tostring(t):split(': ')[2] .. '(table) = {}\r'
end
str = table.concat(str)
return str
end
for k, v in pairs(content) do
if type(v) == "table" then
content[k] = tabToStr(v)
else
content[k] = tostring(v)
end
end
content = table.concat(content)
return content
end
--->万能print
function log(...)
local content = connectContent(...)
print(content)
end