One loop for iterating through multiple Lua tables

泪湿孤枕 提交于 2019-12-14 04:19:26

问题


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

but how about key-value tables?

E.g. something like this:

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

should result in this:

a:  'a'
b:  'b'
c:  'c'
d:  'd'
e:  'e'
f:  'f'

回答1:


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

Note: this implementation does not respect __pairs metamethod.




回答2:


While it's always nice to have an iterator like Egor's, a more efficient solution would simply be

local t1 = {a="a", b="b", c="c"}
local t2 = {d="d", e="e", f="f"}

for key, val in pairs(t1) do
    print(key..": "..val)
end
for key, val in pairs(t2) do
    print(key..":  '"..val)
end

It's simple, concise, and easily understandable.



来源:https://stackoverflow.com/questions/33849777/one-loop-for-iterating-through-multiple-lua-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!