Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why is this not sorting the table?

Asked by
yurhomi10 192
10 years ago
lost = {1,6,0,8,2,5}

table.sort(lost, function(a, b)
   return lost[a] < lost[b]
end)

for i, v in pairs(lost) do
   print(i, v)
end

1 answer

Log in to vote
5
Answered by
jobro13 980 Moderation Voter
10 years ago

You have interpreted wrong how table.sort works. The values passed to the functions are not the indices, but in fact, the values! (That is, lost[a] will be a, and lost[b] is b).

What you mean is:

lost = {1,6,0,8,2,5}

table.sort(lost, function(a, b)
   return a < b
end)

for i, v in pairs(lost) do
   print(i, v)
end

1
THANK YOU ! yurhomi10 192 — 10y
Ad

Answer this question