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

Can I have some help with table.sort?

I'm having quite a bit of trouble creating a custom function for table.sort that I need to use since I'm sorting values that have both numbers and letters.

Here's what I have so far:

table.sort(backpackitems, function(a, b)
	local aNum = tonumber(string.sub(a.Name, 8))
	local bNum = tonumber(string.sub(b.Name, 8))
end)

After I get the number values from the strings, how do I put one table item in front of the other if its number is the larger of the two?

1 answer

✓ Accepted answer

The function argument to table.sort is asking "is a 'smaller than' b?"

It might be easier to think of it as a less function then:

function itemLess(a, b)
	local function number(x)
		return tonumber(x.Name:sub(8)) or math.huge
	end
	return number(a) < number(b)
end

table.sort(backpackitems, itemLess)

This itemLess you can pretend is like < and get what you'd expect:

itemLess({Name="abcdefgh12"}, {Name="abcdefgh20"}) --> true

itemLess({Name="abcdefgh12"}, {Name="abcdefgh11"}) --> false

itemLess({Name="abcdefgh100"}, {Name="abcdefgh20"}) --> true

itemLess({Name="abcdefgh200"}, {Name="abcdefgh10"}) --> false

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