Sorting a table with numbers/letters numerically

I have a table in my code that looks like this:

local tbl = {"Flashlight1", "Apple2", "ZSlot8", "Zslot4", "Zslot7", "Zslot6", "Zslot5", "Zslot3", "Zslot9"}

I want to sort it in this way with table.sort

Would it work if i did it as if it was all numbers and no text and used tonumber()
And if an entry did not have a number, could it go to the beginning?

1 Like

Not sure what you mean.

Anyway, you can sort based on any ordering you desire. Here’s how you can sort based on the number at the end:

table.sort(tbl, function(a, b)
    local na, nb = a:match("%d+$"), b:match("%d+$")
    return na < nb
end)

%d matches digits, %d+ matches 1 or more digits, and $ forces it to end with 1 or more digits.

i dont believe this works with 2 digit numbers (when it ends with 10, i think it gets 0 and it goes to start of array)

Whoops you’re right, it needs to convert the strings to numbers before comparing, just pass the output of each match call to tonumber.

So tonumber(a):match() and tonumber(b):match()?

No. That’d be like
local result1 = tonumber(a)
local result2 = result1:match()

Since result1 is a number, there is no match method. match is a string method, not a number method.

Try

table.sort(tbl, function(a, b)
    local na, nb = tonumber(a:match("%d+$")), tonumber(b:match("%d+$"))
    return na < nb
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.