2

I have a table that I need to print out in order. I know LUA tables are not ordered.. but I am having a terrible time printing it out in an ordered way. I have cut a dozen code snips from this site and I just can not get it to work.

Say I have a table like this:

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

How can I get it to print like this...

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

Using a line like this inside a loop...

print(k..', '..v)
1

1 Answer 1

2

You can store the key/value pairs in an array, sort the array by the second element, and loop through that array. (This example uses tail recursion, because that's how I felt like doing it.)

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.