title: Lua - Sort table and randomize ties
body: <p>
  I have a table with two values, one is a <em>name</em> (string and unique) and the other is a number value (in this case <em>hearts</em>). What I want is this: sort the table by <em>hearts</em> but scramble randomly the items when there is a tie (e.g. <em>hearts</em> is equal). By a standard sorting function, in case of ties the order is always the same and I need it to be different every time the sorting function works.
  This is anexample:</p>
  
  <pre class="lang-lua prettyprint-override"><code>tbl = {{name = "a", hearts = 5}, {name = "b", hearts = 2}, {name = "c", hearts = 6}, {name = "d", hearts = 2}, {name = "e", hearts = 2}, {name = "f", hearts = 7}}
  sort1 = function (a, b) return a.hearts &gt; b.hearts end
  sort2 = function (a, b)
      if a.hearts ~= b.hearts then return a.hearts &gt; b.hearts
      else return a.name &gt; b.name end
  end
  
  table.sort(tbl, sort2)
  
  local s = ""
  for i = 1, #tbl do
      s = s .. tbl[i].name .. "(" .. tbl[i].hearts .. ") "
  end
  print(s)
  </code></pre>
  
  <p>Now, with the function <code>sort2</code> I think I quite got the problem. The problem is, what happens when <code>a.hearts == b.hearts</code>? In my code it just orders the ties by their name, not what I want. I have two ideas:</p>
  
  <ol>
  <li>First scramble randomly all the items in the table, then apply <code>sort1</code>.</li>
  <li>Add a value to every element of the table, called <code>rnd</code>, that is a random number. Then in <code>sort2</code>, when <code>a.hearts == b.hearts</code> order the items by <code>a.rnd > b.rnd</code>.</li>
  <li>In <code>sort2</code>, when <code>a.hearts == b.hearts</code> generate randomly true or false and return it. It doesn't work, and I understand that this happens because the random true/false makes the order function crash since there could be inconsistencies.</li>
  </ol>
  
  <p>I don't like 1 (because I would like to do everything inside the sorting function) and 2 (since it requires to add a value), I would like to do something like 3 but working. The question is: is there a way do to this in a simple manner, and what is an optimal way of doing this? (maybe, method 1 or 2 are optimal and I don't get it).</p>
  
  <p><em>Bonus question.</em> Moreover, I need to fix an item and sort the others. For example, suppose we want <code>"c"</code> to be first. Is it good to make a separate table with only the items to sort, sort the table and then add the fixed items?</p>