Let’s say I have a Table:
local t = {"apple", "mango", "banana"}
I want to sort the Table in alphabetical order so the Script returns
{
[1] = "apple",
[2] = "banana",
[3] = "mango"
}
and not
{
[1] = "apple",
[2] = "mango",
[3] = "banana"
}
Thanks for help!
table.sort(t, function(a, b)
return a:byte() < b:byte()
end)
local t = {"apple", "mango", "banana"}
local r = table.sort(t, function(a, b)
return a:byte() < b:byte()
end)
print(r)
returns nil.
table.sort
doesn’t actually return anything. It modifies the original table that you inserted.
1 Like
I see:
local t = {"apple", "mango", "banana"}
table.sort(t, function(a, b) return a:byte() < b:byte() end)
print(t)
works.
Kacper
(Kacper)
March 16, 2021, 2:41pm
#6
This does not sort in alphabetical order basing on the whole word, it only sorts using the first letter. In order to sort in alphabetical order you simply have to do the following:
local t = {"ac", "ab"}
table.sort(t) -- gives {"ab", "ac"}
When using a:byte() < b:byte() the order in that specific table wouldn’t change, but “ab” should be before “ac”.
3 Likes
Would this work if I used numbers instead? such as
local t = {"12", "11"}
table.sort(t)
azqjanna
(azqjanna)
November 16, 2022, 4:16am
#8
No, this will still sort these “Alphabetically”, since the elements are still strings.
Oh so, It’s not gonna magically become “11” and “12” and nothing will change?
azqjanna
(azqjanna)
November 16, 2022, 4:29am
#10
No, it just wont be sorted the way you think. It will think “100” is less than “2”, because ‘1’ is less than ‘2’.
can u suggest what method should I use in order for it to become properly arranged?
azqjanna
(azqjanna)
November 16, 2022, 4:51am
#12
If you must sort a list of strings representing numbers by their value, you can do this:
local list = {"10", "200", "350", "9" }
table.sort(list, function(a, b)
return tonumber(a) < tonumber(b)
end)
print(list)
1 Like