Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associative Array sorting value

I have the following code that should return me an sorted array on the basis of its 'pos' value.

local tables = {}

table.insert(tables,{ ['pos']=2, ['name'] = 'C' })
table.insert(tables, {['pos']=1, ['name'] = 'A' })
table.insert(tables,{ ['pos']=30, ['name'] = 'D'} )


function comp(w1,w2)
    if tonumber(w1['pos']) > tonumber(w2['pos']) then
        return true
    end
end

table.sort(tables, comp)

for key,val in pairs(tables) do
    print(val['name'])
end

Result is:

D C A

Expected (alphabetically sorted by its "pos"):

A, C, D

Whats wrong?

like image 473
frgtv10 Avatar asked Jan 19 '26 05:01

frgtv10


1 Answers

From the documentation of table.sort(table [, comp]) in PIL:

[comp] This order function receives two arguments and must return true if the first argument should come first in the sorted array

so change the function to:

function comp(w1,w2)
    return w1['pos'] < w2['pos']
end

note tonumber and the if are both unnecessary here.

as @lhf pointed out this can be made simpler still:

table.sort(tables, function(w1, w2) return w1.pos < w2.pos end)
like image 85
ryanpattison Avatar answered Jan 20 '26 21:01

ryanpattison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!