您的位置:首页 > 编程语言 > Lua

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递归的文章。

如果大家有兴趣,可以根据上面的例子自己再扩展,加入一些约束条件,例如最大打印多长的表,最多可以打印表的深度是多少等等,有兴趣的同学可以根据这个例子大开脑洞。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: