Table Manipulation (`table`)

The table module provides optimized C algorithms for manipulating array sequences, sorting with custom predicates, and transferring memory slices.

Function Reference

Function Signature Description
table.insert(list, [pos,] value) (table, [int,] any) → void Inserts value at position pos, shifting elements up. If pos is omitted, appends to the end.
table.remove(list, [pos]) (table, [int]) → any Removes and returns the element at pos, shifting elements down. Defaults to removing the last element.
table.sort(list, [comp]) (table, [func]) → void Sorts list elements in-place. comp(a, b) returns true if a should precede b.
table.concat(list, [sep, [i, [j]]]) (table, [str, [int, [int]]]) → str Concatenates list elements from index i to j with optional separator string sep.
table.pack(...) (...) → table Packs arguments into a table with an extra key n containing the exact parameter count.
table.unpack(list, [i, [j]]) (table, [int, [int]]) → (...) Returns all elements from list[i] to list[j] as multiple return values. Defaults to 1..#list.
table.move(a1, f, e, t, [a2]) (tbl, int, int, int, [tbl]) → tbl High-speed block copy of elements from a1[f..e] into destination a2[t..].

Sorting with Custom Predicates

table_sorting.lua
players = {
    { name = "Aria", score = 250 },
    { name = "Bryn", score = 490 },
    { name = "Cael", score = 120 }
}

-- Sort descending by score:
table.sort(players, function(p1, p2) {
    return p1.score > p2.score
})

for i, p in ipairs(players) {
    print(string.format("#%d %s - %d pts", i, p.name, p.score))
}