Table sorting bug

i have bug with table sorting. I need default table sort like

"1, 2, 3, 4..."

but I get

"100, 1000, 1001, 1050, 110, 120, 1200, 1300, 150, 1500, 1600, 200, 2500, 350..."

here is my script:

way = game.StarterGui.Shop.Frame.Scroll:GetChildren()
local costs = { }
for i,v in ipairs(way) do
   if v:IsA("Frame") then
      costs[i] = v.Buy.Text
   end
end
table.sort(costs)
1 Like

Remove the way variable and try doing this :

for i, v in pairs(game.StarterGui.Shop.Frame.Scroll:GetChildren()) do

instead of :

for i,v in ipairs(way) do

1 Like

same :frowning: i also tried to add “tonumber(costs[i])” in loop, but didn’t help

1 Like

Not sure if this is going to do anything, but it’s worth a shot.

way = game.StarterGui.Shop.Frame.Scroll:GetChildren()
local costs = { }

for i,v in ipairs(way) do
   if v:IsA("Frame") then
      costs[i] = tonumber(v.Buy.Text)
   end
end

table.sort(costs)
1 Like

thanks! it worked. I tried with:

way = game.StarterGui.Shop.Frame.Scroll:GetChildren()
local costs = { }

for i,v in ipairs(way) do
   if v:IsA("Frame") then
      costs[i] = v.Buy.Text
      tonumber(costs[i])
   end
end

table.sort(costs)

but it didn’t work

From my understanding, that doesn’t work because you aren’t actually changing the value of costs[i], instead it’s just returning the value and turning it into a number.

1 Like

this is because you’re sorting an array of strings, therefore it’s sorted “alphabetically”, where “1” comes before “2” in the alphabet

you need to use a custom sort callback to convert to number and check the values against each other:

local costs = {}

-- for loop
---- table.insert(costs, v.Buy.Text)

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

-- do something with the sorted costs table

however, if you inserted into the costs table as a number (table.insert(costs, tonumber(Buy.Text))), you shouldn’t need to use a custom sort callback

you may also want to consider adding some sort of validation. if this is custom user input being accepted, you want to ensure that the text being entered is exclusively numeric

3 Likes