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