lua table输出函数(可以输出嵌套表格)

本文介绍了一个Lua语言中用于打印各种类型变量(特别是table)的函数PrintTable。该函数支持输出到标准输出或文件,并可控制输出格式。适用于调试及序列化需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

function PrintTable(o, f, b)
if type(f) ~= "function" and f ~= nil then
error("expected second argument %s is a function", tostring(f))
end
if type(b) ~= "boolean" and b ~= nil then
error("expected third argument %s is a boolean", tostring(b))
end
p = f or io.write
b = b or false
if type(o) == "number" or
type(o) == "function" or
type(o) == "boolean" or
type(o) == "nil" then
p(tostring(o))
elseif type(o) == "string" then
p(string.format("%q",o))
elseif type(o) == "table" then
p("{/n")
for k,v in pairs(o) do
if b then
p("[")
end

PrintTable(k, p, b)

if b then
p("]")
end

p(" = ")
PrintTable(v, p, b)
p(",/n")
end
p("}")

end
end


最近因为工作需要,学习了lua,呵呵,挺有意思了,甚至让我萌生了回去继续学习以前学过一下的python.
因为常用vim编写lua,调试不是太方便,所以根据programming in lua写了上面这个函数,用起来还算方便,当
需要输出到文件的时候就指定第二参数,或者通过io.output改变io.write的行为.第三参数是指定需要输出
到文件并能重新读出来时的[]号的,具体原因就不多讲了,看看programming in lua 就知道了.

下面是个示例:
a = {[{100, 200}] = { 300, 400}, 200, { 300, 500}, abc = "abc"}
PrintTable(a, io.write, true)

输出结果如下:
{
[1] = 200,
[2] = {
[1] = 300,
[2] = 500,
},
[{
[1] = 100,
[2] = 200,
}] = {
[1] = 300,
[2] = 400,
},
["abc"] = "abc",
}

其实还是合法的lua语句,可以用来作为序列化语句,或者配置文件.没有经过严格测试,仅作为抛砖引玉.
对于新手,提示一下,可以通过在此函数前加上module("PrintTable", package.seeall),并将此文件保存在
类似lualibs的库目录,然后就可以通过在你自己的程序中用require "PrintTable"来使用此函数了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值