Associatively sorting a table by value in Lua

前端 未结 6 1759
星月不相逢
星月不相逢 2020-11-28 11:47

I have a key => value table I\'d like to sort in Lua. The keys are all integers, but aren\'t consecutive (and have meaning). Lua\'s only sort function appears to be table.

6条回答
  •  隐瞒了意图╮
    2020-11-28 12:36

    You seem to misunderstand something. What you have here is a associative array. Associative arrays have no explicit order on them, e.g. it's only the internal representation (usually sorted) that orders them.

    In short -- in Lua, both of the arrays you posted are the same.

    What you would want instead, is such a representation:

    items = {
        {1004, "foo"},
        {1234, "bar"},
        {3188, "baz"},
        {7007, "quux"},
    }
    

    While you can't get them by index now (they are indexed 1, 2, 3, 4, but you can create another index array), you can sort them using table.sort.

    A sorting function would be then:

    function compare(a,b)
      return a[1] < b[1]
    end
    
    table.sort(items, compare)
    

提交回复
热议问题