如何按顺序打印LUA表?

时间:2018-03-27 00:20:00

标签: sorting printing lua lua-table

我有一张桌子需要按顺序打印出来。我知道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 个答案:

答案 0 :(得分:2)

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

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)
相关问题