3

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?

0

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.