Sorting Table in aplhabetical order?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

Alphabetical ordered table

  1. What is the issue?
local Table = {
	"B",
	"K",
	"O",
	"P",
	"V",
	"G"
}

Table = table.sort(Table)

for i, v in pairs(Table) do
	print(i, v)
end
  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

I want to know how to make an alphabetically ordered table

That’s the script, not the issue. I want to know what the output says and what it is or isn’t doing exactly. However, I think I know the problem.
Your error is probably something along the lines of a nil value on line 12. The reason is that table.sort doesn’t return anything. In other words, table.sort just sorts the table, it has no output. Get rid of the Table = on line 10, to change line 10 to this:
table.sort(Table)

3 Likes

Assuming this is only for uppercase letters, here’s what you are looking for:

local Characters = {}
for i = 1, 26 do
    Characters[string.char(i + 64)] = i
end

function SortAlphabetically(Table)
    table.sort(Table, function(A, B)
        return Characters[A] < Characters[B]
   end)
end

local ExampleInput = {
    'B',
    'C',
    'A'
}
SortAlphabetically(ExampleInput)
print(table.concat(ExampleInput, ' ')) -- A B C
2 Likes
print("bb" < "c") --> true

By default, strings use alphabetical order, not length. The OP’s code was correct apart from the fact that he thought table.sort returned the sorted table.

(he just needs to make sure to use the < operator)

@JarodOfOrbiter’s solution will fix the problem.

@avozzo You don’t need to use string.char and add the numbers to a table, comparison operators on strings use the alphabet automatically

1 Like