Lua 打印table表内容

--PrintTable.lua
local PrintTb = {}
local function _t_2string(depth)
	local _t_str = ""
	for i = 1, depth do
		_t_str = _t_str .. "    "
	end
	return _t_str
end


local function table_is_num_array(t)
	local count = 0
	for k, v in pairs(t) do
		count = count + 1
		if type(k) ~= "number" or math.floor(k) ~= k then

			return false
		end
	end

	return count == #t
end

local function table_loop(t_string, t, depth, is_num_array)
	for k, v in pairs(t) do
		if type(k) == "number" and type(v) == "table" then
			t_string = t_string .. _t_2string(depth) .. "["..tostring(k).."]".. " = "
			t_string = t_string .. "{\n"
			t_string = table_loop(t_string, v, depth + 1)
			t_string = t_string .. _t_2string(depth) .. "},\n"
		elseif type(v) == "table" then
			t_string = t_string .. _t_2string(depth) .. tostring(k) .. " = "
			t_string = t_string .. "{\n"

			if table_is_num_array(v) then
				t_string = t_string .. _t_2string(depth + 1)
			end
			t_string = table_loop(t_string, v, depth + 1, table_is_num_array(v))

			if table_is_num_array(v) then
				t_string = t_string .. "\n" .. _t_2string(depth) .. "},\n"
			else
				t_string = t_string .. _t_2string(depth) .. "},\n"
			end
		elseif type(v) == "boolean" then
			t_string = t_string .. _t_2string(depth) .. "[\""..tostring(k).."\"]".. " = " .. tostring(v) .. ",\n"
		elseif type(v) == "function" then
			t_string = t_string .. _t_2string(depth) .. tostring(k).. " = function,\n"
		else
			if is_num_array then
				t_string = t_string .. tostring(v) .. ","

			else
				t_string = t_string .. _t_2string(depth) .. k .. " = "

				if type(v) == "string" then
					t_string = t_string .. "\"" .. tostring(v) .. "\"" .. ",\n"
				else
					t_string = t_string .. tostring(v) .. ",\n"
				end
			end
		end
	end
	return t_string
end


function PrintTb:print(t, name)
	local str = "{\n"
	str = table_loop(str, t, 1) .. "}\n"
	print(name.." = "..str)
end

return PrintTb

将上述代码保存为一个lua文件,例如:PrintTable.lua, 使用示例:

--main.lua
local PrintTb = require("PrintTable")

local t = {
	num = 10,
	list = {1,2,3,4,54,5,6,76,7,801},
	array = {{x = 1, y = 2, z = 3},{x = 10, y = 20, z = 30},{x = 100, y = 200, z = 300},},
	test_info = {
		info = {
			id = 10000,
			msg = "shiguangqingqianchu",
			list = {"sdfa","werqwer","sfawerqwe"},
		}
	},
	multi_t = {
		multi_t1 = {
			multi_t2 = {
				multi_t3 = {
					str = "hello lua!",
					list = {1,23,3,4,5,56},
					func = function(a, b)
						return a + b
					end
				}
			}
		}
	},
	func = function(a, b)
		return a + b
	end
}

PrintTb:print(t, "t")

示例结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春休夏末

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值