Skip to content

Table helpers

rootbeer.tbl is a small set of table utilities for module authors. The most important one is sorted_pairs — Lua's built-in pairs() has no defined order, which produces nondeterministic generator output: different content on every run, noisy diffs, unstable tests.

Module code that iterates a user-supplied map should prefer sorted_pairs unless insertion order is explicitly part of the contract.

lua
local tbl = require("rootbeer.tbl")

-- Deterministic iteration over a user map.
for alias, command in tbl.sorted_pairs(aliases) do
    print(alias, command)
end

See the authoring principles for the full convention.

API Reference

rootbeer.tbl.sorted_keys(t)

Returns the keys of a table as a sorted array. Useful when you need the keys themselves (e.g. to count them or iterate twice). For the common case of "iterate this map in order", prefer sorted_pairs.

lua
local tbl = require("rootbeer.tbl")
for _, k in ipairs(tbl.sorted_keys({ b = 1, a = 2 })) do
  print(k) -- "a", "b"
end

Parameters

ttable<K, V>
The table whose keys to extract.

Returns

<K>[]keys — Keys of t, sorted ascending.

rootbeer.tbl.sorted_pairs(t)

A drop-in replacement for pairs() that yields (key, value) pairs in sorted-key order. Use this anywhere generator output must be stable across runs.

lua
local tbl = require("rootbeer.tbl")
for k, v in tbl.sorted_pairs({ b = 2, a = 1 }) do
  print(k, v) -- "a 1", "b 2"
end

Parameters

ttable<K, V>
The table to iterate.

Returns

fun():<K>?, <V>iterator