Lua从入门到放弃--打印表Demo
2016-04-20 11:24
411 查看
前两天借给朋友600大洋,今天他还给我400,我就问他怎么才400大洋,他告诉我说我借给他钱的时候,里面有两张假的~~~~~我TMD就想问问,用支付宝转账还TMD会有假钱。
function printTable(tbl, indent)
local output = {}
if type(tbl) == "table" then
table.insert(output, "{\n")
for key, value in pairs(tbl) do
local innerIndent = (indent or " ") .. (indent or " ")
table.insert(output, innerIndent .. tostring(key) .. " = ")
table.insert(output,
value == tbl and "<self>," or printTable(value, innerIndent)
)
end
table.insert(output, indent and (indent or "") .. "},\n" or "}")
else
if type(tbl) == "string" then tbl = string.format("%q", tbl) end
table.insert(output, tostring(tbl) .. ",\n")
end
return table.concat(output)
end
t = {1, 2, 3, {4, 5, 6, {7, 8, 9}}}
print(printTable(t, nil))
--[[输出结果为:
{
1 = 1,
2 = 2,
3 = 3,
4 = {
1 = 4,
2 = 5,
3 = 6,
4 = {
1 = 7,
2 = 8,
3 = 9,
},
},
}
]]
上面只是写了一个简单的demo,其中参数1为要打印的表,参数2为缩进符,代码上没什么难度,大多数语法都是我们之前讲过的,只是加入了一个递归,如果对递归不理解的同学,可以私密我或者我之后再更新一篇关于lua递归的文章。
如果大家有兴趣,可以根据上面的例子自己再扩展,加入一些约束条件,例如最大打印多长的表,最多可以打印表的深度是多少等等,有兴趣的同学可以根据这个例子大开脑洞。
function printTable(tbl, indent)
local output = {}
if type(tbl) == "table" then
table.insert(output, "{\n")
for key, value in pairs(tbl) do
local innerIndent = (indent or " ") .. (indent or " ")
table.insert(output, innerIndent .. tostring(key) .. " = ")
table.insert(output,
value == tbl and "<self>," or printTable(value, innerIndent)
)
end
table.insert(output, indent and (indent or "") .. "},\n" or "}")
else
if type(tbl) == "string" then tbl = string.format("%q", tbl) end
table.insert(output, tostring(tbl) .. ",\n")
end
return table.concat(output)
end
t = {1, 2, 3, {4, 5, 6, {7, 8, 9}}}
print(printTable(t, nil))
--[[输出结果为:
{
1 = 1,
2 = 2,
3 = 3,
4 = {
1 = 4,
2 = 5,
3 = 6,
4 = {
1 = 7,
2 = 8,
3 = 9,
},
},
}
]]
上面只是写了一个简单的demo,其中参数1为要打印的表,参数2为缩进符,代码上没什么难度,大多数语法都是我们之前讲过的,只是加入了一个递归,如果对递归不理解的同学,可以私密我或者我之后再更新一篇关于lua递归的文章。
如果大家有兴趣,可以根据上面的例子自己再扩展,加入一些约束条件,例如最大打印多长的表,最多可以打印表的深度是多少等等,有兴趣的同学可以根据这个例子大开脑洞。
相关文章推荐
- Lua中的操作系统库
- Lua从入门到放弃--元表(操作符)
- 浅析 Android 动画:自定义 Interpolator 与 TypeEvaluator
- Lua从入门到放弃--元表
- Lua math库
- lua C++对象内存管理
- Lua根据秒数返回时间串00:00:00
- Thrift lua example
- Lua学习笔记
- Lua函数[转]
- Lua与C++ 交互
- 自定义lua输出
- lua 函数库汇总
- lua面向对象与基于lua的状态机实现
- aodh M版本新特性 - queue between alarm evaluator and alarm notifier
- lua中的pairs和ipairs差别
- Lua学习笔记PartⅡ
- Wireshark Lua: 一个从RTP抓包里导出H.264 Payload,变成264裸码流文件(xxx.264)的Wireshark插件
- C++混合编程之idlcpp教程Lua篇(7)
- c++调用lua