Table that sorts numerically rather than alphabetically?

I think I finally found what’s causing my waypoints script to start messing up. At first it was a problem with the waypoints in a table not being sorted. And then someone taught me about table.sort. It was a good fix for a while until i realized it was sorting alphabetically rather than numerically. All of the waypoints are named numbers, and this is how they are sorted normally in studio (and in the script as you can see with the print). Is there a way to have a table sort these names numerically?

Screenshot_25

	local waypoints = map.EnemyPaths[tostring(mob.WaypointsType.Value)]:GetChildren()
	
	table.sort(waypoints, function(a,b)
		return a.Name < b.Name
	end)
	
	for i, waypoint in pairs(waypoints) do
		print(waypoint.Name)
	end

Could be for one of two reasons, I’m not 100% sure but doing both should hopefully fix it:

1- It’s comparing the codepoints of the names. For example, if you do print('a' > 'b'), it won’t error, it’ll just be false because a’s codepoint is 97 whereas b is 98. So instead try doing tonumber() on the name (return tonumber(a.Name) < tonumber(b.Name))
2- Try using ipairs instead of pairs for iterating through an array, pairs is made for dictionaries, mixed-key tables and tables with gaps whereas ipairs guarantees to iterate the table in order.

1 Like

Solution #1 ended up working out. Thank you so much for the help!

1 Like