Lua in pairs with same order as it's written

前端 未结 3 1529
慢半拍i
慢半拍i 2020-12-11 20:09

Is there any way to loop trough a table like the one below in the same order as it\'s written?

local tbl = {
    [\"hello\"] = 1,
    [2] = 2,
    [50] = 3,
         


        
3条回答
  •  孤街浪徒
    2020-12-11 21:01

    No. There's no "as written in the source" order to tables. (Consider that not all keys necessarily exist in the source.) lua has no concept of "in order" for non-contiguous integer keys.

    If you want a specific order you get to keep that order yourself manually in some way.

    If you don't have any integer keys in your table then you can use those as your order (and use ipairs to loop those keys and index the value as the key to get the real value).

    If your original values are the order you want to sort in then you can loop and reverse map to get a table that you can iterate with ipairs once done.

提交回复
热议问题