Sorting Tables!

Sorting tables is fun and easy to use! Find out how!

by lnsertYourself

Author Avatar

Est. read time: 12 minutes

Introduction

Hello Lua Learners! You just clicked on a tutorial about sorting tables. So I’m sure you want to learn how to sort tables now, correct?

There are limitless possibilities of sorted tables. In this tutorial, I will show you how to sort a simple table and in the end, we will see a practical application of it! So let’s get started!

Background

In order to fully understand this tutorial, it is required that you have a basic understanding of tables before moving on: creating tables and understanding indexes. And also how to iterate through tables.

The Scripting

First, let’s create an arbitrary table of numbers we want to sort.

local numbers = {1,6,8,4,3,54,5,3,5,2,7,56,8,2,9,2,3,5}

Next, let’s output the table so we can see our before and after the sort. To do this, we will use the table.unpack() function. When given a single argument, this function takes a table and returns every entry separated by spaces. Let’s try that now!

print(table.unpack(numbers))

1 6 8 4 3 54 5 3 5 2 7 56 8 2 9 2 3 5

As you can see, the output displays all the entries in the order we initialized it.

So the table is unsorted. Now let’s sort it 😊

We will use the table.sort() function to do this. Can you guess what it does? 😆

table.sort() receives two arguments. First, the table we want to sort, and second a function that tells how we want to sort the table. I will write the code first, and then explain the function part after.

table.sort(numbers, function(a,b)
    return a < b
end)

So we said before, table.sort() takes two arguments: the table and a function to describe how we want the table to be sorted. So what does the return a < b mean?

I’m not going to dive deep into it, but basically the function takes two indexes from our table and put them as a and b then compares them. Then returns a true or false value. And the table will sort these indexes based on the return value.

An easy way to remember how to do this is to organize the letters alphabetically, a and b, like I just did. And the arrow will describe whether you want an ascending ordered table or a descending ordered table.

Here’s how to remember:

So < means less than. This would mean we want the smallest number to be first (ascending order).

*> means greater than. This would mean we want the largest number to be first (descending order).

So given our easy-to-remember strategy, return a < b would give us an ascending ordered table, because we use < meaning less, meaning we want our first number to be the least.

Okay, so now that we just sorted our table, let’s print out the table once again using the table.unpack() function!

print(table.unpack(numbers))

1 2 2 2 3 3 3 4 5 5 5 6 7 8 8 9 54 56

As you can see, our table is perfectly ordered!

The Final Script

local numbers = {1,6,8,4,3,54,5,3,5,2,7,56,8,2,9,2,3,5} -- Our arbitrary table

print(table.unpack(numbers)) -- Prints our table

table.sort(numbers, function(a,b) -- This is how we sort our table
    return a < b -- In ascending order
end)

print(table.unpack(numbers)) -- Print our newly sorted table

1 6 8 4 3 54 5 3 5 2 7 56 8 2 9 2 3 5 1 2 2 2 3 3 3 4 5 5 5 6 7 8 8 9 54 56

Application

In this application section, we are going to simulate a local leaderboard! Let’s say we want to display the player and their coins. The player with the most coins is at the top and goes in descending order. In this tutorial, we will populate an arbitrary table, but you can obtain a table of the player’s names and their stats however you’d like for your game!

local tbl = {
    {"boatbomer", 25},
    {"lnsertYourself", 21},
    {"jakehead20", 39},
    {"caiomgt", 9},
    {"coryn13", 55}
}

print(table.unpack(tbl))

table: 0x320542cca5e1be09 table: 0xa0b14ffe0e68f089 table: 0xcba7a059b1f42869 table: 0xdbce191151ef3dc9 table: 0x394b7d71488d54c9

So why are we getting some strange output? This is because our table consist of other tables! So we are printing the table representation, not the actual content! So if we want to print out the content as-is, we have to iterate through the table:

local tbl = {
    {"boatbomer", 25},
    {"lnsertYourself", 21},
    {"jakehead20", 39},
    {"caiomgt", 9},
    {"coryn13", 55}
}

for _,subTable in ipairs(tbl) do
    print(table.unpack(subTable))
end

boatbomer 25 lnsertYourself 21 jakehead20 39 caiomgt 9 coryn13 55

So because we had tables within tables, we had to print them out in a particular way. Do we have to do the same for sorting? YES!

The second parameter of table.sort() expects a function that takes two indexes from the table. So somehow we have to obtain the coin values within our table to compare. And we can achieve this like so:

table.sort(tbl, function(a,b)
    local aNum = a[2]
    local bNum = b[2]
    return aNum > bNum
end)

What did we just do? Well, a and b are tables from our original table, tbl. And we know that our coin values are at the second index of those tables. So we retrieve those numbers and compare them. Now, before we used < to compare the numbers. This is because we wanted to organize the numbers in ascending order. Since we want a leaderboard, we use > because we want the largest number to be the first in the list.

The Final Script

local tbl = {  -- Table in {“Player”, coins} format
    {"boatbomer", 25},
    {"lnsertYourself", 21},
    {"jakehead20", 39},
    {"caiomgt", 9},
    {"coryn13", 55}
}

print("Unorganized:")

for _, subTable in ipairs(tbl) do
    print(table.unpack(subTable)) -- Print the content of our tables within the table
end

table.sort(tbl, function(a,b)
    local aNum = a[2] -- Coin value of a
    local bNum = b[2] -- Coin value of b
    return aNum > bNum -- Return their comparisons, < for ascending, > for descending
end)

print("Organized:")

for _, subTable in ipairs(tbl) do
    print(table.unpack(subTable)) -- Print our finished, organized table :)
end

Unorganized: boatbomer 25 lnsertYourself 21 jakehead20 39 caiomgt 9 coryn13 55

Organized: coryn13 55 jakehead20 39 boatbomer 25 lnsertYourself 21 caiomgt 9

Conclusion

Knowing how to sort tables can be the best tool in your toolbox. When you work with tables, sorting them will often make workflow easier and more efficient. So I hope you implement this technique to your own games!

Have a nice day, get to scripting, and much more! 😊

View in-game to comment, award, and more!