Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

table.sort not sorting numbers?

I got alot of values in a folder that are all named a specific number, I want to sort these numbers with table.sort but something isn't working correctly because my result is:

10, 11, 11, 11, 110, 12, 122, 1268, 15, 16, 18, 20, 29, 38, 40, 95

local children = script.results:GetChildren()
local sorted = {}

for i=1,#child do
	local text = children[i].Name
	tonumber(text)
	table.insert(sorted, text)
end
table.sort(sorted)

print(table.concat(sorted, ', '))

2 answers

✓ Accepted answer

You need to use tonumber before inserting them in the table, because if you use table.sort on a table with strings, it sorts them in alphabetical order (using every character from \0 to \255). That is why it sorts all the digits that start with 1 in the beginning, and then does the same for the second digit, etc.

I think you might've knew this, but it is not working because you are not doing anything with the return value of tonumber(text).

To fix this, you just need to tonumber it and put its return value in the table.. Your code should look like

local children = script.results:GetChildren()
local sorted = {}

for i=1,#child do
    --local text = children[i].Name (you don't need a variable, just makes it longer)
    --tonumber(text) (tonumber returns a string, it doesn't change what that variable holds)
    table.insert(sorted, tonumber(text))
end
table.sort(sorted)

print(table.concat(sorted, ', '))

Hope this helps!

Figured it out myself by:

for i=1,#child do
	local text = 0
	text = tonumber(child[i].Name)
	table.insert(sorted, text)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.