Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can I have some help with table.sort?

Asked by
Klamman 220 Moderation Voter
8 years ago

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

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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
Ad

Answer this question