如何使用键,值和索引遍历Lua表

时间:2019-03-24 16:55:54

标签: arrays loops lua iterator iteration

我想遍历一个看起来像这样的表

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可能吗?

2 个答案:

答案 0 :(得分:3)

迭代器:

$sql    = "SELECT a.cusName
                , a.cusMob
                , a.invoiceNo
                , a.invoiceDate
                , a.total_VAT
                , a.bill_tot
                , b.itemsName 
                , b.rate
                , b.amt_vat
                , ROUND(b.amt_vat + inull(b.amount,0), 2) as amount
            FROM invoices a
            LEFT JOIN invoice_items b ON a.invoiceID=b.invoiceid
            WHERE a.invoiceDate between '$getfromdate' 
                and '$gettodate' and a.status IS NULL 
            order by a.invoiceID desc";

用法:

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 :(得分:2)

使用协程的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