代码之家  ›  专栏  ›  技术社区  ›  aJynks

如何按顺序打印LUA表?

  •  2
  • aJynks  · 技术社区  · 7 年前

    我有一张表格需要按顺序打印出来。我知道LUA的桌子没有订。。但我在有序地打印出来时遇到了麻烦。我从这个网站上剪下了十几个代码片段,但我就是无法让它正常工作。

    假设我有一张这样的桌子:

    local tableofStuff = {}
          tableofStuff['White'] = 15
          tableofStuff['Red'] = 55
          tableofStuff['Orange'] = 5
          tableofStuff['Pink'] = 12
    

    我怎样才能把它打印成这样。。。

    Red, 55
    White, 15
    Pink, 12
    Orange, 4
    

    在循环中使用这样的线。。。

    print(k..', '..v)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   luther    7 年前

    您可以将键/值对存储在一个数组中,按第二个元素对数组排序,然后循环遍历该数组。(这个例子使用尾部递归,因为我就是这么想的。)

    local tableofStuff = {}
    tableofStuff['White'] = 15
    tableofStuff['Red'] = 55
    tableofStuff['Orange'] = 5
    tableofStuff['Pink'] = 12
    
    -- We need this function for sorting.
    local function greater(a, b)
      return a[2] > b[2]
    end
    
    -- Populate the array with key,value pairs from hashTable.
    local function makePairs(hashTable, array, _k)
      local k, v = next(hashTable, _k)
      if k then
        table.insert(array, {k, v})
        return makePairs(hashTable, array, k)
      end
    end
    
    -- Print the pairs from the array.
    local function printPairs(array, _i)
      local i = _i or 1
      local pair = array[i]
      if pair then
        local k, v = table.unpack(pair)
        print(k..', '..v)
        return printPairs(array, i + 1)
      end
    end
    
    local array = {}
    makePairs(tableofStuff, array)
    table.sort(array, greater)
    printPairs(array)