Associative Array sorting value

lua, lua-table, sorting

Solution

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)

Problem

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?

Original source