Thread Tools Display Modes
Prev Previous Post   Next Post Next
07/17/14, 07:47 AM   #1
zgrssd
AddOn Author - Click to view addons
Join Date: May 2014
Posts: 280
Sorting nested tables

As part of my LibConstantMapper I wanted to add a simple sorting of the result set.
My results are well formed arrays, where each entry is a table containing a "key" and "value" index.
I want those nested tables to be sorted - first by value, then by key (in the odd case a duplicate value exists).
As far as I understand table.sort accepts a function. That function takes 2 parameters (element a and b) and returns true if a < b. So I wrote this function:
Lua Code:
  1. local function CompareKeyValuePair(a, b)
  2.   --assert valid input
  3.   assert(type(a) == "table" and a.key ~= nil and a.value ~= nil, "argument a must be a table containing a 'key' and 'value' string-index")
  4.   assert(type(b) == "table" and b.key ~= nil and b.value ~= nil, "argument b must be a table containing a 'key' and 'value' string-index")
  5.  
  6.   --Sort by value first, key second
  7.   return (a.value < b.value) or (a.key < b.key)
  8. end

And call it like this:
Lua Code:
  1. if result ~= {} then
  2.   table.sort(result, CompareKeyValuePair)
  3. end
I checked with a d() message, it actually goes into the if block.
But the result does not seems to be ordered.
Anything I overlooked?
  Reply With Quote
 

ESOUI » Developer Discussions » General Authoring Discussion » Sorting nested tables


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off