打印Lua表结构,可用于项目中

新建一个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)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值