如何按顺序打印LUA表格?

我有一个需要按顺序打印的表格。我知道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)
点赞
用户3574628
用户3574628

你可以将键/值对存储在一个数组中,通过第二个元素排序该数组,然后循环遍历该数组。(此示例使用尾递归,因为我想这样做。)

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

-- 我们需要这个函数来排序。
local function greater(a, b)
  return a[2] > b[2]
end

-- 用哈希表中的键/值对填充数组。
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

-- 从数组中打印键/值对。
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)
2018-03-27 01:48:51