user1225905
user1225905

Reputation: 95

How to get the ordering of an array in lua

Is there a (fast) way in lua to sort an array and also get the ordering, e.g.

a = {4,3.2,1,7}

=> ordering would be 3,2,1,4 (because a[3]=1, a[2]=3.2, ...)

Upvotes: 1

Views: 107

Answers (1)

lhf
lhf

Reputation: 72402

Try the code below. It sorts an array of indices using the values for comparison.

a = {4,3.2,1,7} 
o = {}   
for i=1,#a do
    o[i]=i
end    
table.sort(o,function (x,y) return a[x]<a[y] end)    
for i=1,#o do
    print(i,o[i],a[o[i]])
end

Upvotes: 4

Related Questions