新建一个Lua文件,能让所有Lua文件访问到
这里我以 MyPrint.lua 为例子
local MyPrint = {}
function MyPrint.TablePrint(root, flag, depthMax, excludeKey, excludeType)
if type(root) ~= "table" then
return print("table_print value : ",root)
end
local huanHang
local moreSpace
local shuxian
local oneSpace
if flag then
huanHang = ""
moreSpace = ""
shuxian = ""
oneSpace = ""
else
huanHang = "\n"
moreSpace = " "
shuxian = "|"
oneSpace = " "
end
depthMax = depthMax or 7 -- 默认7层
local cache = { [root] = "." }
local depth = 0
if flag then print(flag) end
if not flag then print("{") end
local function _dump(t,space,name)
local temp = {}
for k, v in pairs(t) do
local key = tostring(k)
if type(k) == "string" then
key = '\"' .. tostring(k) .. '\"'
end
if type(v) == "table" then
if cache[v] then
table.insert(temp,space .. "["..key.."]" .. " = " .. " {" .. cache[v] .. "}, ")
else
local new_key = name .. "." .. tostring(k)
cache[v] = new_key .. "[" .. tostring(v) .. "]"
-- table 深层判断
depth = depth + 1
if depth >= depthMax or (excludeKey and excludeKey == k) then
table.insert(temp,space .. "["..key.."]" .. " = " .. "{ ... }")
else
local tableStr = _dump(v, space .. (next(t, k) and shuxian or " ") .. string.rep(oneSpace, #key<4 and 4 or #key),new_key)
if tableStr then -- 非空table
table.insert(temp, space .. "["..key.."]" .. " = " .. "{")
table.insert(temp,tableStr)
table.insert(temp,space .. "},")
else
table.insert(temp,space .. "["..key.."]" .. " = " .. "{ },")
end
end
depth = depth - 1
end
else
local vType = type(v)
if not excludeType or excludeType ~= vType then
if vType == "string" then
v = '\"' .. v .. '\"'
else
v = tostring(v) or "nil"
end
table.insert(temp,space .. "["..key.."]" .. " = " .. v .. ",")
end
end
end
return #temp>0 and table.concat(temp,huanHang) or nil
end
local allTableString = _dump(root, moreSpace, "")
if not flag then print(allTableString or "") end
if not flag then print("}") end
if flag then
local sqlStr = string.format("{%s}", allTableString)
if sqlStr == "{nil}" then sqlStr = "{}"end
return sqlStr
else
return allTableString
end
end
return MyPrint
测试:
local MyPrint = require "MyPrint"
local t = {
name = "csdn",
sex = 0,
level = 1,
list = {
{1,2,3},
{4,5,6},
}
}
MyPrint.TablePrint(t)
MyPrint.TablePrint(10000)