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?
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