如何在 Lua 中使用键、值和索引循环 Lua 表

我想循环一个看起来像以下的表

function add(t, k, v, ...)
    if k ~= nil then
        t[k] = v
        t[#t+1] = k
        return add(t, ...)
    end
    return t
end

my_table = add({ }, "a", 5, "b", 4, "c", 3)

for i,k in ipairs(my_table) do
    local v = my_table[k]
    print(k, v)
end

结果为:

a - 5

b - 4

c - 3

但是,我想使用索引、键和值循环表,使其看起来像这样:

1 - a - 5

2 - b - 4

3 - c - 3

在 Lua 中是否可能实现这一点呢?

点赞
用户1847592
用户1847592

迭代器:

function triples(t)
  local function next_triple(tbl, idx)
    idx = idx + 1
    local k = tbl[idx]
    if k ~= nil then
      return idx, k, tbl[k]
    end
  end
  return next_triple, t, 0
end

用法:

local a = {"q", "w", "e", q = 11, w = 22, e = 33}
for i, k, v in triples(a) do
  print(i, k, v)
end

输出:

1   q   11
2   w   22
3   e   33
2019-03-24 19:32:16
用户7552
用户7552

使用协程的 Egor 的 triples 函数的替代实现:

function triples(t)
  return coroutine.wrap(function()
    for i, k in ipairs(t) do
      coroutine.yield(i, k, t[k])
    end
  end)
end
2019-03-25 14:26:49