Sorting and Comparators
Lesson 27 of 48 in Coddy's Lua for C Developers course.
C qsort and Lua table.sort both rearrange their input. Their comparator contracts differ. A C comparator receives pointers to elements and returns a negative integer, zero, or a positive integer. A Lua comparator receives values and returns a boolean that says whether the first value must precede the second. Both need a consistent ordering. The C example compares integers without subtracting them, avoiding overflow for extreme values. The Lua example uses the built-in ascending order. Neither sort promises to preserve the original order of equivalent elements.
C
#include <stdio.h>
#include <stdlib.h>
static int compare(const void *left, const void *right) {
int a = *(const int *)left;
int b = *(const int *)right;
return (a > b) - (a < b);
}
int main(void) {
int items[] = {3, 1, 2};
qsort(items, sizeof items / sizeof items[0], sizeof items[0], compare);
printf("%d\n", items[0]);
return 0;
}Lua
local items = {3, 1, 2}
table.sort(items)
print(items[1])Porting trap
Do not translate a C three-way result directly into Lua: zero and negative numbers are truthy. Return a strict comparison such as a < b. Also, table.sort returns no sorted table; keep the original reference.
Challenge
EasyInput lines are integers. Return them sorted descending and comma-separated; preserve duplicates. Return empty for no values.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules3Iteration and Flow
Numeric for and Limitswhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsParsing with Lua PatternsModules and requireStatus Codes to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler