lua: iterate through all pairs in table

后端 未结 1 2031
悲哀的现实
悲哀的现实 2020-12-10 11:58

I have a sparse lua table and I need to iterate over it. The Problem is, it seems that lua begins the iteration at 1, and terminates as soon as it finds a nil value. Here\

相关标签:
1条回答
  • 2020-12-10 12:01

    You must use pairs instead of ipairs.

    tab={}
    
    tab[1]='a'
    tab[2]='b'
    tab[5]='e'
    
    for k, v in pairs(tab) do print(k, v) end
    

    Will output (in any order):

    1   a
    2   b
    5   e
    

    ipairs iterates over sequential integer keys, starting at 1 and breaking on the first nil pair.

    pairs iterates over all key-value pairs in the table. Note that this is not guaranteed to iterate in a specific order.

    0 讨论(0)
提交回复
热议问题