1

I looked at a few other questions here but they didn't seem to explicitly solve my question.

I am attempting to sort an array of image objects based on their timestamp. In doing this noticed that table.sort was not returning the result I expected. I then created the following code which is simplified for clarity but shows the same unexpected behavior.

My question is: what am I doing wrong so that all individual comparisons show a proper true/false value yet the end result is not in ascending order?

EDIT: I have found that placing the comparison directly within table.sort call resolves the issue, so it appears that using an external function causes this erratic behavior, can anyone explain why? And is there a way to alleviate that?

images = {1,2,4,6,5,3,88,34,8}

local function comp_time(first, second) --returns true if 'first' was taken before 'second'
        ret = first < second
        print(first..'  <  '..second..'  :  '..tostring(ret))
    return ret
end

print('unsorted:')
for i,image in ipairs(images) do
    print(i..'  :  '..image)
end
table.sort(images, function(image1, image2) comp_time(image1, image2) end)
print('sorted:')
for i,image in ipairs(images) do
    print(i..'  :  '..image)
end

The result is:

unsorted:
1  :  1
2  :  2
3  :  4
4  :  6
5  :  5
6  :  3
7  :  88
8  :  34
9  :  8
8  <  1  :  false
5  <  1  :  false
8  <  5  :  false
2  <  5  :  true
5  <  88  :  true
4  <  5  :  true
5  <  3  :  false
6  <  5  :  false
5  <  34  :  true
6  <  5  :  false
5  <  34  :  true
8  <  4  :  false
2  <  4  :  true
8  <  2  :  false
6  <  2  :  false
2  <  6  :  true
2  <  2  :  false
2  <  4  :  true
6  <  4  :  false
34  <  1  :  false
88  <  1  :  false
34  <  88  :  true
3  <  88  :  true
88  <  3  :  false
88  <  88  :  false
88  <  1  :  false
3  <  1  :  false
sorted:
1  :  1
2  :  3
3  :  88
4  :  34
5  :  5
6  :  4
7  :  6
8  :  2
9  :  8
2
  • 1
    function(image1, image2) return comp_time(image1, image2) end Commented Feb 28, 2019 at 18:11
  • Thanks Mike, that was my problem. Seems obvious in retrospect. If you make it an answer instead of a comment I can accept it. Commented Feb 28, 2019 at 18:47

1 Answer 1

1

The reason that it wasn't working before is that your function wasn't returning a value, so it returns nil, which is falsy (i.e. it's not true). So whichever order the table happened to be iterated over was how the elements ended up being "sorted."

To fix this, you just need to change your function to return a value, i.e.

table.sort(images, function(image1, image2) return comp_time(image1, image2) 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.