Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua table sort does not work

I have the below program code which tries to sort a given list. I have tried various options and it still doesn`t work.

local List = {}    
List[143] = "143"    
List[145] = "145"    
List[120] = "120"       
List[178] = "178"   
table.sort(List, compare)

compare function is defined as

function compare(a, b)    
    if tonumber(a) < tonumber(b) then    
        return true    
    end
end

Above table.sort does not work to any order. I just want to sort it to increasing numerical order. If you have any ideas about this please help me. Thanks in advance

like image 568
user2951607 Avatar asked Jan 14 '14 14:01

user2951607


2 Answers

table.sort (and much of the rest of the table.* functions) is defined only for operations on array-like tables. That means tables with contiguous integer keys from 1..n. Your table doesn't meet those criteria.

like image 197
Etan Reisner Avatar answered Nov 02 '22 22:11

Etan Reisner


The keys of that table do not satisfy requirements of that function. The keys must start at 1 and sequentially increase to N, as per Lua ref manual ("Sorts table elements in a given order, in-place, from table[1] to table[n]"). Try

local List = {}
List[1] = "143"    
List[2] = "145"    
List[3] = "120"       
List[4] = "178"   
table.sort(List, compare)

or even better

local List = {"143", "145", "120", "178"}
table.sort(List, compare)
like image 32
Oliver Avatar answered Nov 02 '22 22:11

Oliver