pairsByKeys update

Posted by WillFa on Sat 26 Jul 2008 10:40 AM — 2 posts, 8,705 views.

USA #0
I came across pairsByKeys while looking for a way to sort a table alphabetically. As luck would have it, the first thing I tried to alphabetize was a Wildcards table from a trigger with named parameters. It barfs - doesn't like comparing numbers to strings.

So, a quick update that I thought I'd share; maybe Nick would incorporate it in the next release of MC.


function pairsByKeys (t, f)
  local a = {}
  -- build temporary table of the keys
  for n in pairs (t) do 
    table.insert (a, tostring(n)) 
  end
  table.sort (a, f)  -- sort using supplied function, if any
  local i = 0        -- iterator variable
  return function () -- iterator function
    i = i + 1
    return tonumber(a[i]) or a[i], t[tonumber(a[i]) or a[i]]
  end  -- iterator function
end -- pairsByKeys

return pairsByKeys



So now if you have a table with indices and keys, you can get a sorted listing of it.

Hope it helps.
Amended on Sat 26 Jul 2008 10:50 AM by Nick Gammon
Australia Forum Administrator #1
Also see: http://www.gammon.com.au/forum/?id=8698