如何在lua中使用递归打印嵌套表?

  • 本文关键字:打印 递归 嵌套 lua lua
  • 更新时间 :
  • 英文 :


我想用递归打印这个表,而不是用for循环。我尽量避免重复代码。

local t = {x=0, y=5, other={10,10,10,11}}
function DeepPrint (t)
local request_headers_all = ""
for k, v in pairs(t) do
if type(v) == "table" then
for k1, v1 in pairs(v) do
local rowtext = ""
rowtext = string.format("[%s %s] ",k, v1)
request_headers_all = request_headers_all .. rowtext
end 
else
local rowtext = ""
rowtext = string.format("[%s %s] ", k, v)
request_headers_all = request_headers_all .. rowtext
end
end
return request_headers_all
end
print(DeepPrint (t))

期望输出(顺序无关):

[y 5] [x 0] [other 10] [other 10] [other 10] [other 11]

您可以简单地删除内部循环并使用v的值再次调用DeepPrint -表:

local t = {x=0, y=5, other={10,10,10,11}}
function DeepPrint (t)
local request_headers_all = ""
for k, v in pairs(t) do
if type(v) == "table" then
request_headers_all = request_headers_all .. "[" .. k .. " " .. DeepPrint(v) .. "] "
else
local rowtext = ""
rowtext = string.format("[%s %s] ", k, v)
request_headers_all = request_headers_all .. rowtext
end
end
return request_headers_all
end
print(DeepPrint (t))

生产:

[y 5] [x 0] [other [1 10] [2 10] [3 10] [4 11] ] 

请注意,您不会按顺序获得这些。哈希是无序的,所以你不能保证x会在y之前。

更新:删除纯数组的索引

local t = {x=0, y=5, other={10,10,10,11}}
function DeepPrint (t)
local request_headers_all = ""
for k, v in pairs(t) do
if type(v) == "table" then
request_headers_all = request_headers_all .. "[" .. k .. " " .. DeepPrint(v) .. "] "
else
local rowtext = ""
if type(k) == "string" then
rowtext = string.format("[%s %s] ", k, v)
else
rowtext = string.format("[%s] ", v)
end    
request_headers_all = request_headers_all .. rowtext
end
end
return request_headers_all
end

输出:

[y 5] [x 0] [other [10] [10] [10] [11] ] 

相关内容

  • 没有找到相关文章

最新更新