Lesson 30 of 55
9 mins readPython Custom Sorting with table.sort
In Plain English
`table.sort(list [, comp])` sorts array elements in-place. An optional comparator function `comp(a, b)` returns true if `a` should precede `b`.
Deep Dive: How It Works
In-Place Mutation: Modifies the original sequence in memory.
Default Behavior: Sorts ascending using the `<` operator.
Strict Weak Ordering: Comparator must return true ONLY if `a < b` (never true for equal elements).
Core Rules to Remember

In-Place Sorting: `table.sort(t)` sorts elements without allocating a new table.

Custom Comparator: Pass `function(a, b) return a.field > b.field end` for custom ranking.
Live Interactive Example
Hit Run Code to see it liveSorting Players by Score Descending
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: table.sort ranked players in descending score order.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Sort Numbers Descending
Declare `local nums = { 5, 1, 9, 3 }`.
Sort descending with `table.sort(nums, function(a, b) return a > b end)`.
Print `"Sorted: " .. table.concat(nums, ", ")`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.