Menu
CoddyTech

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 icon

Challenge

Easy

Input 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for C Developers

Practice on your own: Online Lua compiler