A Bug In My Tool (Table.sort Related)

I made a tool that adds a menu to the instrument box for sorting the instrument list. Now I have a bug that I need some advice to get rid of.

I’m using table.sort and my problem is that it keeps shuffling elements around if the values compared in table.sort() are equal.

table.sort(map_table, function(a, ![B)](https://files.renoise.com/forum/emoticons/default/cool.gif) return a.size > b.size end)  

I tried experimenting by using >= but this will result in an error. Any approach suggested to solve this is appreciated! I am hoping for a simple solution before i start to remake my routines too much.

EDIT: Solved.

  
 table.sort(map_table, function(b, a)  
 if a.size == b.size then return a.original_position > b.original_position  
 else return a.size < b.size  
 end   
 end)  
  

Did you cut and paste that straight from the code?

Lua is case sensitive.

You have a capital B in your function declaration, but a small b in your procedure.

That must have been some error on the forums. Never mind that :) Everything is working, but I need to keep equal elements “unaffected” so to speak.

Solved. Sorry for bothering. And thanks to conner_bw too.

  
 table.sort(map_table, function(b, a)  
 if a.size == b.size then return a.original_position > b.original_position  
 else return a.size < b.size  
 end   
 end)  
  

In the Lua manual it says:

“The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.” [Source. ]

Google search says this is done “on purpose for speed” and that “you should write your own sort”, or something.

Not sure if this is your problem. I looked at the code and can confirm the bug. I don’t have an easy workaround. I did notice that if I do the following map_size() at around line ~78

  
 local tmp = { }  
 for _,val in ipairs(map_table) do  
 table.insert(tmp, val.size)  
 end   
 table.sort(tmp)  
 rprint(tmp)  
  

The sorting is correct.

Tada!