Sorting Tables in Lua
25
Nov
Sometimes, you’ll need to sort a table in alphabetical or numerical order. Fortunately, Lua provides an easy function called table.sort() . This function will sort a table in alphabetical order.
Here’s how:
-- The original table
local cards = {"heart","spades","clubs","diamonds"}
-- Sort the table
table.sort(cards)
-- Print the new contents of the table
for k,v in ipairs(cards) do
print(k,v)
end
To sort a table, just pass in the table as a parameter to the function. And that’s it!