一个循环遍历多个Lua表 [英] One loop for iterating through multiple Lua tables
本文介绍了一个循环遍历多个Lua表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在同一循环中遍历多个Lua表?
Is it possible to iterate through multiple Lua tables with the same loop?
要遍历索引表,我可以执行以下操作:
For looping through indexed tables I can do something like this:
local t1 = {"a", "b", "c"}
local t2 = {"d", "e", "f"}
local num = #t1+#t2
for i=1, num, do
local j
local val
if i <= #t1 then
j = i
val = t1[j]
else
j = i-#t1
val = t2[j]
end
-- Do stuff
end
但是键值表呢?
例如像这样的东西:
local t1 = {a="a", b="b", c="c"}
local t2 = {d="d", e="e", f="f"}
for key, val in pairs(t1) or pairs(t2) do
print(key..": '"..val.."'")
end
应导致以下结果:
a: 'a'
b: 'b'
c: 'c'
d: 'd'
e: 'e'
f: 'f'
推荐答案
function pairs(t, ...)
local i, a, k, v = 1, {...}
return
function()
repeat
k, v = next(t, k)
if k == nil then
i, t = i + 1, a[i]
end
until k ~= nil or not t
return k, v
end
end
local t1 = {a="a", b="b", c="c"}
local t2 = {d="d", e="e", f="f"}
for key, val in pairs(t1, t2) do
print(key..": '"..val.."'")
end
注意:此实现不遵守__pairs
元方法.
Note: this implementation does not respect __pairs
metamethod.
这篇关于一个循环遍历多个Lua表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文