santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

the base library: arrays, strings, tables, functions, numbers, and fractional order keys

santoku is the base library of the framework: plain Lua 5.1 modules for arrays, strings, tables, functions, numbers, ordering keys, errors, validation, time, randomness, and async control flow. Every example is live. Edit the code and press Run to execute it here, in a Lua interpreter compiled to WebAssembly.

Details
  • santoku has no dependencies beyond Lua itself and a few small C helpers.
  • The examples run from basics to advanced.

santoku.array

Array pipelines

arr.range, arr.filter, arr.map and arr.sum build a range, filter it, map it and fold it, all in place.

local arr = require("santoku.array")
local t = arr.range(1, 10)
arr.filter(t, function (v)
  return v % 2 == 0
end)
arr.map(t, function (v)
  return v * v
end)
print("squares:", arr.concat(t, ", "))
return arr.sum(t)

In-place or copying transforms

Most transforms come in pairs, such as sort and sorted, map and mapped, filter and filtered. The bare name mutates its argument, and the -ed form returns a fresh table.

local arr = require("santoku.array")
local str = require("santoku.string")
local words = { "pear", "fig", "apple", "banana" }
local by_len = arr.sorted(words, function (a, b)
  return #a < #b
end)
print("shortest first:", arr.concat(by_len, " "))
print("original intact:", arr.concat(words, " "))
local dedup = arr.sort({ 3, 1, 2, 3, 1 }, { unique = true })
print("sorted unique:", arr.concat(dedup, " "))
local caps = arr.mapped(words, str.upper)
print("mapped copy:", arr.concat(caps, " "))
print("middle:", arr.concat(arr.slice(words, 2, 3), " "))
print("last two:", arr.concat(arr.takelast(words, 2), " "))
return arr.concat(arr.reverse(arr.filtered(words, function (w)
  return #w > 3
end)), " ")
Details
  • Each transform takes the array first and the function second, as in arr.mapped(t, fn, ...).
  • Extra arguments pass through to fn after the element.
  • sort takes either a comparator or an options table with unique = true.

Stacks, queues and edits

push, pop and shift make stacks and queues. insert, remove, find and includes edit and query an array.

local arr = require("santoku.array")
local stack = {}
arr.push(stack, "a", "b", "c")
local _, top = arr.pop(stack)
print("popped:", top)
local queue = { "first", "second", "third" }
local _, head = arr.shift(queue)
print("shifted:", head)
arr.insert(queue, 1, "zeroth")
arr.remove(queue, 2, 2)
print("queue:", arr.concat(queue, " "))
local v, i = arr.find(queue, function (x)
  return x == "third"
end)
print("found:", v, "at index", i)
print("includes:", arr.includes(queue, "third", "missing"))
local row = { "Ada", "Lovelace", 1815, "London", "mathematics" }
local person = arr.tabulate(row, { rest = "tags" }, "first", "last", "born")
print("record:", person.first, person.last, person.born)
return arr.concat(person.tags, ", ")
Details

tabulate turns a positional row into a named record, with a rest key for the tail.

Grouping and reshaping

group buckets by a key function, and partition splits on a predicate. zip and unzip pair and unpair, chunked cuts windows, flatten unnests, and uniqued dedups without sorting.

local arr = require("santoku.array")
local nums = arr.range(1, 10)
local by_parity = arr.group(nums, function (v)
  return v % 2 == 0 and "even" or "odd"
end)
print("evens:", arr.concat(by_parity.even, " "))
local small, large = arr.partition(nums, function (v)
  return v <= 5
end)
print("small:", arr.concat(small, " "))
print("large:", arr.concat(large, " "))
local zipped = arr.zip({ "x", "y", "z" }, { 1, 2, 3 })
print("second pair:", zipped[2][1], zipped[2][2])
local letters, values = arr.unzip(zipped)
print("unzipped:", arr.concat(letters, ""), arr.concat(values, ""))
local windows = arr.chunked(nums, 4)
print("chunks:", #windows, "last:", arr.concat(windows[#windows], " "))
local flat = arr.flatten({ 1, { 2, 3 }, { 4, { 5 } } })
print("flattened one level:", #flat, "items")
return arr.concat(arr.uniqued({ 1, 2, 2, 3, 3, 3 }), " ")

Numbers in arrays

sum, mean, max and min (value and index) work on arrays of numbers, as does small vector math: dot products, magnitudes, and scalar and elementwise arithmetic.

local arr = require("santoku.array")
local xs = { 3, 1, 4, 1, 5, 9, 2, 6 }
print("sum:", arr.sum(xs), "mean:", arr.mean(xs))
local m, mi = arr.max(xs)
print("max:", m, "at index", mi)
print("mean of first four:", arr.mean(xs, 1, 4))
local a = { 1, 2, 3 }
local b = { 4, 5, 6 }
print("dot:", arr.dot(a, b))
print("magnitude:", arr.magnitude({ 3, 4 }))
arr.scale(a, 10)
print("scaled:", arr.concat(a, " "))
arr.addv(a, b)
print("elementwise sum:", arr.concat(a, " "))
arr.add(b, 100)
return arr.concat(b, " ")
Details

Range arguments let every one of these functions work on a slice without a copy.

Lifting iterators

imap, ifilter, ireduce and icollect consume any Lua iterator (gmatch, ipairs, your own) without an intermediate table first. icollect takes an optional limit.

local arr = require("santoku.array")
local str = require("santoku.string")
local words = arr.imap(str.upper, ("lift map over any iterator"):gmatch("%a+"))
print("mapped:", arr.concat(words, " "))
local long = arr.ifilter(function (w)
  return #w > 3
end, ("one two three four"):gmatch("%a+"))
print("filtered:", arr.concat(long, " "))
local first3 = arr.icollect(3, ("a b c d e"):gmatch("%a+"))
print("first three:", arr.concat(first3, " "))
return arr.ireduce(function (acc, field)
  return acc + #field
end, 0, ("ab,cde,f"):gmatch("[^,]+"))

santoku.string

Splitting and matching

splits cuts a string on a Lua pattern and keeps every field, empty ones included. matches collects every match of a pattern into an array.

local str = require("santoku.string")
local arr = require("santoku.array")
local parts = str.splits("one,two,three", ",")
print("fields:", #parts, arr.concat(parts, "|"))
local kept = str.splits("key=value", "=", true)
print("with delimiter:", arr.concat(kept, " "))
local nums = arr.map(str.matches("10 39.5 46.8", "%S+"), tonumber)
print("parsed sum:", nums[1] + nums[2] + nums[3])
return arr.concat(str.splits("path/to/some/file.lua", "/"), " > ")
Details
  • santoku.string is a superset of Lua's string table. find, sub, match, gmatch, gsub, lower, upper, rep, byte, char and format are all there, so code never needs string.* directly.
  • Splitting "a,,b" on "," gives a, an empty string and b.
  • Pass true as the third argument to keep the delimiters as their own elements between the fields.
  • Pass "left" or "right" to attach each delimiter to the field before or after it.

interp and parse

interp interpolates by name, by position, or with printf formats through %fmt#(key). parse is its inverse, and maps capture groups tagged with #(key) into a named table.

local str = require("santoku.string")
local num = require("santoku.num")
print(str.interp("Hello %who, %adj to meet you!", {
  who = "World",
  adj = "nice",
}))
print(str.interp("%1 %3 %2", { "a", "b", "c" }))
print(str.interp("pi is %.3f#(pi)", { pi = num.pi }))
print(str.interp("%(num_to_display)", { num_to_display = 7 }))
print(str.interp("showing %view_cap of %(total rows), 50% done.", {
  view_cap = 20,
  ["total rows"] = 400,
}))
local t = str.parse("2023-10-26 09:10:26",
  "(%d+)#(year)-(%d+)#(month)-(%d+)#(day) (%d+)#(hour):(%d+)#(min):(%d+)#(sec)")
print("year:", t.year, "hour:", t.hour)
return t.month
Details
  • A short key %key is a name of letters, digits and underscores that starts with a letter or underscore.
  • %1 takes digits only, so %1_c is the first value followed by _c.
  • A period after a key stays text.
  • %(key) takes any key whose parentheses balance.
  • A % that starts none of these forms stays as written.

Predicates and trimming

These functions do everyday string chores: prefix and suffix tests, trimming with custom patterns, common prefixes across many strings, occurrence counts, human-readable number formatting, and quoting.

local str = require("santoku.string")
print("starts:", str.startswith("santoku.array", "santoku."))
print("ends:", str.endswith("init.lua", ".lua"))
print("trimmed:", "[" .. str.trim("  padded  ") .. "]")
print("custom trim:", str.trim("__flag__", "_*"))
print("stripped:", str.stripprefix("santoku.array", "santoku."))
print("common:", str.commonprefix("santoku.array", "santoku.string", "santoku.table"))
print("count:", str.count("banana", "an"))
print("empty:", str.isempty("   "), str.isempty("x"))
print("nilempty:", str.nilempty(""), str.nilempty("x"))
print("hasword:", str.hasword(" - "), str.hasword("a_1"))
print("digits:", str.digits("2024-10-30"), str.ucfirst("santoku"))
print("filled:", str.isfilled(" x "), str.orempty(nil) == "", str.orempty(12))
print("boundary:", str.isboundary("ab cd", 3), str.isboundary("ab cd", 2))
print("squash:", "[" .. str.squash("  a \t b\n c  ") .. "]")
print("striptags:", str.striptags("<b>bold</b> text"))
print("quoted:", str.quote("say \"hi\""))
print("unquoted:", str.unquote(str.quote("say \"hi\"")))
return str.format_number(1234567.89)
Details
  • quote(s[, q[, e]]) wraps s in q, a double quote by default.
  • quote escapes e and q inside s with e. e is a backslash by default.
  • unquote reverses quote, and returns s unchanged when s isn't wrapped in q.
  • Since santoku 3.5.0, nilempty(v) returns nil for nil and "", and v otherwise.
  • Since santoku 3.5.0, hasword(s) reports whether s holds a letter, digit or underscore. It returns false for nil.
  • Since santoku 3.5.0, digits(s) keeps only the decimal digits of s. A number goes through tostring first, and nil gives "".
  • Since santoku 3.5.0, ucfirst(s) upper-cases a leading ASCII lowercase letter.
  • Since santoku 3.6.0, isfilled(s) returns the inverse of isempty(s). It's true when s holds a non-space character.
  • Since santoku 3.6.0, orempty(v) returns "" for nil and false, and tostring(v) otherwise. nilempty is its inverse.
  • Since santoku 3.6.0, isboundary(s, i) reports a word boundary before byte i. It's true when exactly one of bytes i - 1 and i is a letter, digit or underscore.
  • Since santoku 3.6.0, squash(s[, opts]) collapses each whitespace run to one space and trims the ends. With opts.nbsp, it first turns each UTF-8 no-break space into a space.
  • Since santoku 5.2.0, striptags(s) removes every span from "<" to the next ">", newlines included. A "<" with no ">" after it stays.

Hashing and encodings

The C core merged into santoku.string covers SHA-256 digests, hex, base64, SHA-1, percent-encoding and UTF-8. It also parses a number out of the middle of a string.

local str = require("santoku.string")
local digest = str.sha256("hello")
print("sha256:", str.to_hex(digest))
print("stream:", str.to_hex(str.sha256_stream():update("hel"):update("lo"):final()))
print("sha1:", str.to_hex(str.sha1("hello")))
print("md5:", str.to_hex(str.md5("hello")))
print("from_hex:", str.from_hex("68656c6c6f"))
local masked = str.xor("secret", "k")
print("xor round trip:", str.xor(masked, "k"))
local b64 = str.to_base64("hello, world")
print("base64:", b64)
print("decoded:", str.from_base64(b64))
print("url-safe:", str.to_base64_url("data?with=symbols"))
print("url-safe decoded:", str.from_base64_url(str.to_base64_url("data?with=symbols", false)))
local enc = str.to_url("a value & more")
print("percent-encoded:", enc)
print("round trip:", str.from_url(enc))
print("path:", str.to_url("/a b/c", { keep = "/", upper = true }))
print("form:", str.to_url("a b&c", { plus = true }), str.from_url("a+b%26c", { plus = true }))
print("lenient:", str.from_url("100%", { lenient = true }))
print("number at offset 2:", str.number("v1.25-beta", 2))
print("utf8_char:", str.utf8_char(99, 97, 102, 233, 8364))
return str.to_hex("\1\2\255")
Details
  • sha1(s), sha256(s) and md5(s) return the raw digest bytes (20, 32 and 16). Wrap them in to_hex or to_base64 to print them.
  • Since santoku 6.1.0, sha256_stream() hashes input that arrives in pieces. s:update(chunk) adds bytes and returns s, and s:final() returns the same 32 bytes sha256 would give for the whole input. A stream raises on any call after final.
  • SHA-1 is there for protocols that require it.
  • to_base64(s, url, pad) and to_base64_url(s, pad) write plain and URL-safe base64. Both pad unless you pass false as the last argument.
  • from_hex, from_base64 and from_base64_url decode. from_base64_url takes padded and unpadded input.
  • from_hex raises "Invalid hex character" on anything but hex digits.
  • utf8_char encodes codepoints as UTF-8, and raises on a surrogate or anything past U+10FFFF.
  • utf8_next(s, i) returns the codepoint at byte i and its width in bytes.
  • utf8_len(s) counts codepoints.
  • utf8_lower and utf8_fold lowercase and case-fold with the Unicode tables.
  • utf8_next, utf8_len, utf8_lower and utf8_fold return nothing on invalid UTF-8.
  • Since santoku 5.2.0, utf8_prev(s, i) returns the codepoint that ends at byte i - 1 and its width, so i - width is where it starts. i defaults to #s + 1. It returns nothing at the start of s and on invalid UTF-8.
  • Since santoku 5.2.0, utf8_trim(s) strips whitespace from both ends, and utf8_squash(s) also collapses each inner run to one space.
  • utf8_trim and utf8_squash use the whitespace set of JavaScript's String.prototype.trim: tab, LF, VT, FF, CR, U+FEFF, U+2028, U+2029 and the Unicode space separators (Zs), no-break space included.
  • utf8_trim and utf8_squash treat a byte that isn't valid UTF-8 as a non-space character and keep it.
  • xor(data, key) XORs data with key repeated to its length. It raises "empty key" on an empty key.
  • to_url(s) percent-encodes every byte except letters, digits and -_.~, with lowercase hex digits.
  • Since santoku 3.5.0, to_url(s, opts) takes options:
OptionEffect
upper = truewrites the hex digits in uppercase, as RFC 3986 recommends
keep = "/"leaves each byte of keep unencoded, such as the slashes of a path
plus = truewrites a space as +, as HTML form encoding does (since santoku 3.6.0)
  • from_url(s) decodes each %XX. It raises "Invalid URL encoding" when fewer than two bytes follow a %.
  • Since santoku 3.6.0, from_url(s, opts) takes options:
OptionEffect
plus = truedecodes + as a space, as HTML form encoding does
lenient = truekeeps a % that two hex digits don't follow, and never raises

HTML escaping

escape_html(s) escapes &, <, > and " for text and quoted attribute values. escape_html_text(s) escapes &, < and > for element text, and leaves quotes.

local str = require("santoku.string")
print(str.escape_html('a & "b" <c>'))
print(str.escape_html("O'Brien & co", { apos = true }))
print(str.escape_html_text('a & "b" <c>'))
print(str.unescape_html("caf&eacute; &copy 2020 &#8217; &#150; &bogus;"))
print(str.unescape_html_attr("?a=1&copy=2&amp;b"))
return str.unescape_html("&amp;amp;")
Details
  • Since santoku 3.6.0, escape_html(s, { apos = true }) also escapes ' as &#39;, for single-quoted attribute values.
  • unescape_html(s) decodes character references in element text the way a browser does.
  • unescape_html knows the HTML 4.01 names plus apos, AMP, LT, GT, QUOT, COPY and REG.
  • unescape_html also decodes legacy names such as &copy without a semicolon, and decimal and hex references with or without a semicolon.
  • 0, surrogates and values past U+10FFFF decode to U+FFFD.
  • 0x80 to 0x9F map through Windows-1252.
  • Unknown or malformed references stay as written.
  • unescape_html_attr(s) adds the attribute-value rule. A legacy name without a semicolon stays as written when = or a letter or digit follows it.
  • Both unescape functions decode one level.

URLs and query strings

parse_url decomposes a URL into scheme, host, port, path segments, search and fragment, and encode_url rebuilds one. to_query and from_query handle bare query strings.

local str = require("santoku.string")
local arr = require("santoku.array")
local u = str.parse_url("https://example.com:8080/docs/intro?page=2&dark=true#usage")
print("scheme:", u.scheme, "host:", u.host, "port:", u.port)
print("path:", arr.concat(u.path, "/"))
local q, ps = str.from_query(u.search)
print("params:", q.page, q.dark)
print("fragment:", u.fragment)
arr.filter(ps, function (p) return p[1] ~= "page" end)
arr.push(ps, { "page", tonumber(q.page) + 1 })
u.search = str.to_query(ps)
print("rebuilt:", str.encode_url(u))
return str.to_query({ sort = "asc" })
Details
  • Since santoku 4.0.0, parse_url has no params field. Pass u.search to from_query.
  • Since santoku 3.4.4, from_query parses the way URLSearchParams does. It drops one leading "?", splits on "&" only, and splits each pair on its first "=".
  • So "?t=agent;cat=fiction" gives t = "agent;cat=fiction".
  • A key with no "=" gets "".
  • "+" decodes to a space.
  • Since santoku 4.0.0, every value is a string, and a malformed escape such as "100%" stays as written.
  • Since santoku 4.0.0, when a key repeats, the first value wins, as URLSearchParams get does.
  • Since santoku 4.0.0, from_query also returns every pair in order, as a list of { key, value }. to_query and to_formdata take that list and keep its order. arr.filter and arr.push on the list do what URLSearchParams delete and append do.
  • The list keeps every value of a repeated key in order, so "?cat=a&cat=b" gives { { "cat", "a" }, { "cat", "b" } }.
  • Since santoku 5.2.0, from_query(s, out, { semicolon = true }) and from_formdata(s, out, { semicolon = true }) also split pairs on ";", as CGI query strings do. So "?t=agent;cat=fiction" gives t = "agent" and cat = "fiction".
  • Since santoku 3.7.0, to_query and to_formdata emit keys in sorted order. So one table gives the same string on every call.
  • Since santoku 3.7.0, to_query(params, { upper = true, plus = true }) takes the upper and plus options of to_url. upper writes hex digits in capitals, and plus writes a space as "+".
  • to_query(params, out) appends to the array out. With options, out moves to the third argument.

Windows-1252 and mojibake since santoku 3.7.0

from_w1252(s) reads Windows-1252 bytes as UTF-8, and to_w1252(s) writes them back. fix_mojibake(s) repairs UTF-8 text that something decoded as Windows-1252, once or several times.

local str = require("santoku.string")
local dash = "\226\128\148"
local once = str.from_w1252(dash)
print("mojibake:", once)
print("fixed:", str.fix_mojibake(once) == dash)
print("twice:", str.fix_mojibake(str.from_w1252(once)) == dash)
print("bytes:", #str.to_w1252("caf\195\169 " .. dash))
return str.from_w1252("caf\233")
Details
  • to_w1252 answers nil when s is not valid UTF-8 or holds a character Windows-1252 lacks.
  • The five bytes Windows-1252 leaves undefined (81, 8D, 8F, 90, 9D) map to the C1 controls of the same number.
  • fix_mojibake replaces a run of characters only when their Windows-1252 bytes decode as UTF-8 with no C1 control. It repeats up to five times, so text encoded twice comes back too.
  • fix_mojibake keeps correct UTF-8 and invalid bytes as they are.

Natural sort order

compare_natural(a, b) is a less-than for arr.sort that ignores case and compares each run of digits by its numeric value. So item 2 sorts before item 10, and v1.2 before v1.10.

local str = require("santoku.string")
local arr = require("santoku.array")
local names = { "item 10", "Item 2", "item 1", "v1.10", "v1.2", "x09", "x9" }
arr.sort(names, str.compare_natural)
print(arr.concat(names, ", "))
return names[1]
Details
  • When two digit runs have the same value, the shorter run sorts first, so x9 comes before x09.
  • Case folding is ASCII only. Accented letters compare by their bytes.

santoku.path

Paths without a filesystem

santoku.path is pure string work on slash-separated paths, so it runs in a browser page as well as natively. santoku-fs re-exports every function, so fs.join is path.join.

local path = require("santoku.path")
local arr = require("santoku.array")
print("join:", path.join("srv", "web", "assets"))
print("join:", path.join("a/", "b"), path.join("srv", "/web"))
print("dirname:", path.dirname("/opt/bin/sort"), path.dirname("stdio.h"))
print("basename:", path.basename("/opt/bin/sort"), path.basename("/home/user/"))
print("extension:", path.extension("release.tar.gz"), path.extensions("release.tar.gz"))
print("strip:", path.stripextension("release.tar.gz"), path.stripextensions("release.tar.gz"))
local parts = {}
for p in path.splitparts("/deploy//web/assets/") do
  parts[#parts + 1] = p
end
print("parts:", arr.concat(parts, " "))
print("stripparts:", path.stripparts("/home/user/a/b/c.txt", 2))
return path.join("a", "b", "c")
Details
  • join inserts a slash only where neither side has one.
  • dirname of a bare name is the current directory.
  • basename of a path that ends in a slash is nil.
  • extension takes the last dot segment, and extensions takes everything from the first dot. stripextension and stripextensions remove them.
  • splitparts iterates components and collapses repeated slashes.
  • stripparts drops n leading components.

Relative paths from a base

relative(fp, base) strips base and the slash after it from fp. It returns . for the base itself, and returns fp unchanged when fp lies outside base.

local path = require("santoku.path")
local err = require("santoku.error")
print("inside:", path.relative("/srv/app/lib/main.lua", "/srv/app"))
print("the base itself:", path.relative("/srv/app", "/srv/app/"))
print("outside:", path.relative("/etc/hosts", "/srv/app"))
local ok, msg = err.pcall(path.relative, "/srv/app/x")
print("no base raises:", not ok, msg)
return path.relative("res/docs/tabs/fs.lua", "res/docs")
Details
  • base is required. santoku.path has no working directory to fall back on, so a missing base raises.
  • fs.relative keeps the old default by passing the current directory.

santoku.table

Paths into nested tables

get, set and update address deep keys as a path array, and create intermediate tables on the way down. merge fills in missing keys recursively and keeps the values already there.

local tbl = require("santoku.table")
local cfg = { server = { host = "localhost" } }
tbl.set(cfg, { "server", "ports", 1 }, 8080)
tbl.update(cfg, { "server", "ports", 1 }, function (p)
  return p + 1
end)
tbl.merge(cfg, {
  server = { host = "ignored", scheme = "https" },
})
print("host:", tbl.get(cfg, { "server", "host" }))
print("scheme:", tbl.get(cfg, { "server", "scheme" }))
print("missing is nil:", tbl.get(cfg, { "server", "tls", "cert" }))
return tbl.get(cfg, { "server", "ports", 1 })

Dictionaries as data

keys, vals and entries project a map into arrays, and from indexes an array by a key function. invert flips keys and values, and equals compares deeply and returns a reason on mismatch.

local tbl = require("santoku.table")
local arr = require("santoku.array")
local ages = { ada = 36, alan = 41, grace = 85 }
print("keys:", arr.concat(arr.sort(tbl.keys(ages)), " "))
print("total:", arr.sum(tbl.vals(ages)))
local by_letter = tbl.from({ "lua", "santoku" }, function (s)
  return s:sub(1, 1)
end)
print("l:", by_letter.l, "s:", by_letter.s)
local flipped = tbl.invert({ a = 1, b = 2 })
print("flipped:", flipped[1], flipped[2])
print("deep equal:", tbl.equals({ x = { 1, 2 } }, { x = { 1, 2 } }))
local _, why = tbl.equals({ x = 1 }, { x = 2 })
return why

Other modules

santoku.functional

These function combinators cover bind for partial application, compose and const. sel and take rearrange argument lists, choose is an expression-level branch, and get turns a field name into an accessor.

local fun = require("santoku.functional")
local arr = require("santoku.array")
local function add (a, b)
  return a + b
end
local inc = fun.bind(add, 1)
local function double (x)
  return x * 2
end
print("compose:", fun.compose(double, inc)(10))
local from_second = fun.sel(fun.id, 2)
print("sel:", from_second("a", "b", "c"))
local print1 = fun.take(print, 1)
print1("kept", "dropped", "dropped")
print("choose:", fun.choose(1 > 2, "yes", "no"))
local names = arr.mapped({ { name = "ada" }, { name = "alan" } }, fun.get("name"))
print("names:", arr.concat(names, " "))
return fun.const(42)()

santoku.num

santoku.num gives rounding, decimal truncation, exponential moving averages, and a C one-dimensional minimizer. The module also re-exports all of math.

local num = require("santoku.num")
print("int:", num.int("  -7x"), num.int("12.7"), num.int("abc", 0))
print("uint:", num.uint("007"), num.uint(" 7"), num.uint("1a", 0))
print("parse_int:", num.parse_int("-12"), num.parse_int("12abc"), num.parse_int("500", 1, 100))
print("round:", num.round(2.5), num.round(2.4))
print("round up to 0.25 steps:", num.round(0.30, 0.25))
local f = function (x) return (x - 2) ^ 2 + 1 end
local xa, xb, xc, fb = num.bracket(f, 0, 0.5)
local x, fx = num.brent(f, xa, xb, xc, fb, 1e-8, 100)
print("minimum:", num.trunc(x, 4), num.trunc(fx, 4))
print("trunc to 3 decimals:", num.trunc(num.pi, 3))
local avg = num.mavg(0.5)
print("mavg:", avg(10), avg(20), avg(30))
print("math included:", num.floor(num.pi), num.max(3, 7))
return num.round(num.pi * 100) / 100
Details
  • round(n) rounds half up to an integer. round(n, step) rounds up to the next multiple of step.
  • bracket(f, x0, h[, maxit]) walks downhill from x0 in steps of h, 40 at most by default.
  • bracket returns xa, xb, xc and f(xb), with xb lower than its neighbors when it succeeds.
  • brent(f, ax, bx, cx, fbx, tol, itmax) refines that bracket and returns the minimizing x and f(x).
  • bracket and brent raise "objective must return a number" when f returns anything else.
  • Since santoku 3.5.0, int(v[, d]) reads the integer v starts with, after optional spaces and a sign, so " -7x" gives -7. A number truncates toward zero.
  • Since santoku 3.5.0, uint(v[, d]) reads a string of decimal digits only, or a whole number of zero or more.
  • int and uint return d, nil by default, for anything else.
  • Since santoku 5.2.0, parse_int(v[, min[, max]]) reads a string that is only an optional sign and decimal digits, or a whole number. It returns nil for anything else, such as "12abc", "1.5" or " 7", for a value outside min and max, and for a magnitude of 2^53 or more.

santoku.fracidx

fracidx.between returns an order key that sorts lexically between two others, so you insert between any two items without renumbering the rest. Use these keys to order list items under concurrent edits.

local fracidx = require("santoku.fracidx")
local arr = require("santoku.array")
local err = require("santoku.error")
local first = fracidx.between(nil, nil)
local second = fracidx.between(first, nil)
local middle = fracidx.between(first, second)
print("first:", first)
print("second:", second)
print("middle:", middle)
print("ordered:", first < middle and middle < second)
local batch = fracidx.between_n(first, second, 3)
print("batch of 3:", arr.concat(batch, " "))
print("bad key rejected:", err.pcall(fracidx.validate, "0oops"))
local prefix = fracidx.gap(first, middle)
local block = { prefix .. fracidx.suffix(0, 2), prefix .. fracidx.suffix(1, 2), prefix .. fracidx.suffix(2, 2) }
print("block:", arr.concat(block, " "))
print("inside:", first < block[1] and block[3] < middle)
print("desc:", fracidx.suffix_desc(0, 2), fracidx.suffix_desc(1, 2))
return fracidx.between(middle, second)
Details
  • between_n generates a balanced batch.
  • validate rejects malformed keys.
  • For a block of derived keys, gap(prev, next) returns a prefix that sorts after prev and before next. next may be nil.
  • prefix .. suffix(i, width) numbers the block in order, and suffix_desc numbers it in reverse.
  • width is 1 to 8 digits and must fit i.

santoku.error

error and assert carry multiple values instead of one string. pcall returns them all, xpcall hands them to your handler, and wrapnil converts nil-plus-message APIs into throwing ones.

local err = require("santoku.error")
local ok, tag, detail, code = err.pcall(function ()
  err.error("db", "connection refused", 111)
end)
print("caught:", ok, tag, detail, code)
local _, val = err.pcall(function ()
  return err.assert(tonumber("42"), "not a number")
end)
print("assert passes values through:", val)
local open = err.wrapnil(function (path)
  return nil, "no such file: " .. path
end)
print("wrapnil:", err.pcall(open, "missing.txt"))
print("checkok:", err.checkok(true, "kept"), err.pcall(err.checkok, false, "io", "closed"))
local function div (a, b)
  if b == 0 then
    err.error("divide by zero", a)
  end
  return a / b
end
return err.xpcall(div, function (msg)
  return "handled: " .. msg
end, 1, 0)
Details
  • checknil(v, ...) does the same as wrapnil for one call already made. It raises the rest of the values when v is nil, and returns them all otherwise.
  • Call checknil as err.checknil(ws:recv_frame()).
  • wrapok and checkok are the same pair for ok-first APIs. A false or nil first value raises the rest, and a true first value is dropped and the rest returned.
  • Outside any pcall the values collapse to a readable colon-joined message.
  • Since santoku 5.0.0, pcall and xpcall run fn in a santoku.co coroutine, so a sleep or an await inside them works in the browser's PUC Lua. copcall and coxpcall are gone.
  • xpcall(fn, handler, ...) passes the extra arguments to fn.

santoku.op

santoku.op holds every Lua operator as a named function. Hand one to reduce, sort and mapped without a wrapper lambda each time.

local op = require("santoku.op")
local arr = require("santoku.array")
print("sum:", arr.reduce({ 1, 2, 3, 4 }, op.add))
print("product:", arr.reduce({ 1, 2, 3, 4 }, op.mul))
local words = arr.sort({ "pear", "fig", "apple" }, op.gt)
print("descending:", arr.concat(words, " "))
print("lengths:", arr.concat(arr.mapped({ "ab", "cdef" }, op.len), " "))
print("logic:", op["not"](nil), op.neg(5))
return op.cat("santoku", ".op")

santoku.validate

Every validator returns true, or false plus a reason and the offending values. That result goes straight into error.assert, so a failed check throws a structured error with the full context attached.

local validate = require("santoku.validate")
local err = require("santoku.error")
print(validate.istruthy("0"), validate.istruthy("00"))
print(validate.isnumber(42))
print(validate.isnumber("42"))
print(validate.between(5, 1, 10))
print(validate.isarray({ 1, 2, 3 }))
print(validate.isarray({ 1, 2, x = 3 }))
local function set_port (cfg, port)
  err.assert(validate.istable(cfg))
  err.assert(validate.between(port, 1, 65535))
  cfg.port = port
  return cfg
end
local ok, msg, bad = err.pcall(set_port, {}, 99999)
print(ok, msg, bad)
return msg
Details
  • Since santoku 3.5.0, istruthy(v) fails for nil, false, "", "0" and 0, the values a form or a Perl script treats as false.
  • istruthy returns false, "Value is not truthy" and v on failure, so use it in a condition or keep only its first result.

santoku.utc

santoku.utc keeps time without timezones: epoch seconds in and out (optionally sub-second), broken-down UTC dates, strftime formatting, calendar-aware shift and trunc, and a stopwatch closure for quick timings.

local utc = require("santoku.utc")
local now = utc.time()
print("epoch:", now)
print("precise:", utc.time(true))
local d = utc.date(now)
print("today:", d.year, d.month, d.day)
print("iso:", utc.format(now, "%Y-%m-%dT%H:%M:%SZ"))
print("tomorrow:", utc.format(utc.shift(now, 1, "day"), "%Y-%m-%d"))
print("midnight:", utc.format(utc.trunc(now, "day"), "%H:%M:%S"))
local lap = utc.stopwatch()
local duration, total = lap()
print("elapsed:", duration, total)
local z = utc.days_from_civil(d.year, d.month, d.day)
print("named:", utc.days[utc.weekday(z) + 1], utc.months[d.month], utc.months_short[d.month])
Details
  • When local time is needed, local_time(fields) reads broken-down local time as epoch seconds.
  • local_offset(t) gives the local UTC offset in seconds.
  • days_from_civil, civil_from_days and weekday convert between dates and day numbers.
  • Since santoku 3.5.0, months and months_short list the English month names, January and Jan first, the names %B and %b give in the C locale.
  • Since santoku 3.5.0, days lists the English day names from Sunday, so days[weekday(z) + 1] names day number z.

Named time zones since santoku 3.7.0

utc.zone_date(t, zone) gives the wall clock fields for epoch t in a named zone, and utc.zone_time(fields, zone) turns wall clock fields back into epoch seconds.

local utc = require("santoku.utc")
local t = 1791856800
local ny = "America/New_York"
local d = utc.zone_date(t, ny)
print("new york:", d.year, d.month, d.day, d.hour, d.zone)
print("iso:", utc.zone_format(t, "%Y-%m-%dT%H:%M:%S%:z", ny))
print("london:", utc.zone_format(t, "%H:%M %Z", "Europe/London"))
print("back:", utc.zone_time({ year = d.year, month = d.month, day = d.day, hour = d.hour }, ny) == t)
print("february:", utc.days_in_month(2100, 2))
return utc.zone_offset(t, ny)
Details
  • zone_offset(t, zone) answers the UTC offset in seconds, the abbreviation and whether daylight time applies.
  • zone_format(t, fmt, zone) runs strftime on the wall clock time. %z writes -0400, %:z writes -04:00 and %Z writes the abbreviation.
  • zone_date adds offset, zone and isdst to the fields utc.date gives.
  • zone_time picks the daylight reading of an hour that repeats in autumn. A time that spring skips reads as standard time, an hour later on the clock.
  • Since santoku 3.8.0, zone_time(fields, zone, opts) takes opts.gap for a skipped time and opts.overlap for a repeated one.
  • gap and overlap each take "earlier" or "later" and pick that instant. gap defaults to "later" and overlap to "earlier". Any other value raises an error.
  • utc.zones lists the names. A table such as { offset = 19800, abbr = "IST" } works as a zone.
  • An unknown zone name raises an error.
RuleZonesFrom
USAmerica/New_York, Chicago, Denver, Los_Angeles, Anchorage1987, with the 2007 change
EUEurope/London, Paris, Berlin1996
AustraliaAustralia/Sydney2008
noneUTC, America/Phoenix, Pacific/Honolulualways
  • days_in_month(y, m) applies the Gregorian leap rule.

Parse date strings since santoku 3.9.0

utc.parse(s, zone, opts) reads an RFC 822, RFC 2822 or ISO 8601 date string as epoch seconds. It returns nil when s isn't a valid date in either format.

local utc = require("santoku.utc")
print("rfc:", utc.parse("Sun, 01 Nov 2026 01:30:00 -0500"))
print("iso:", utc.parse("2026-11-01T06:30:00Z"))
print("named:", utc.parse("1 Jul 2026 09:05 PDT"))
local ny = "America/New_York"
print("eastern:", utc.zone_format(utc.parse("2026-11-01 01:30:00", ny), "%H:%M %Z", ny))
print("skipped:", utc.parse("2026-03-08 02:30:00", ny, { gap = "earlier" }))
print("mysql:", utc.parse("20261101013000", ny))
print("bad:", utc.parse("2026-02-30"))
return utc.parse("2026-11-01T01:30:00.250Z")
Details
  • ISO 8601 takes YYYY-MM-DD, then T, t or a space and HH:MM or HH:MM:SS. A fraction after . or , adds sub-second time.
  • An RFC date takes an optional weekday, the day, the month name, the year, then H:MM or HH:MM:SS. parse ignores a trailing comment in parentheses.
  • A month reads by its first three or more letters, so Sep, Sept. and September all work.
  • Since santoku 5.2.0, parse also reads 14 digits, YYYYMMDDhhmmss, as a MySQL TIMESTAMP column prints them. They carry no zone, so they read as wall clock time in zone.
  • Two-digit years 00 to 49 read as 2000 to 2049, and 50 to 99 as 1950 to 1999. A three-digit year adds 1900. RFC 5322 section 4.3 sets both rules.
  • A zone is Z, +HH:MM, +HHMM, +HH, UT, GMT or an abbreviation from utc.zones, such as EST, PDT, BST or AEST, in any case.
  • A string with no zone reads as wall clock time in zone, which defaults to "UTC". opts.gap and opts.overlap pick the instant for a skipped or repeated hour, as in zone_time.
  • A date alone reads as midnight. 24:00:00 reads as the next midnight, and second 60 rolls into the next minute.
  • parse returns nil for an impossible date such as 2026-02-30, an unknown zone in the string, or trailing text.
  • parse raises when s isn't a string, when zone isn't a known zone, or when opts holds a bad gap or overlap.

Parse time spans since santoku 6.2.0

utc.duration(s) reads a systemd time span, as systemd.time(7) defines it, and returns seconds as a number. Fractions such as 1.5h and 0.25s work.

local utc = require("santoku.utc")
local err = require("santoku.error")
print("compact:", utc.duration("1h30m"))
print("spaced:", utc.duration("1h 30min"))
print("ms:", utc.duration("500ms"))
print("fraction:", utc.duration("1.5d"))
print("bare:", utc.duration("90"))
print("month:", utc.duration("1M"), utc.duration("1m"))
print("unknown:", err.pcall(utc.duration, "5 parsecs"))
return utc.duration("2w 3d")
Details
UnitSuffixesSeconds
microsecondus, usec0.000001
millisecondms, msec0.001
seconds, sec, second, seconds1
minutem, min, minute, minutes60
hourh, hr, hour, hours3600
dayd, day, days86400
weekw, week, weeks604800
monthM, month, months2630016 (30.44 days)
yeary, year, years31557600 (365.25 days)
  • Suffixes are case-sensitive, so M is a month and m is a minute.
  • Parts add up, with or without spaces: 1h30m, 1h 30min and 1 h 30 min all give 5400.
  • A number with no unit counts as seconds, so 90 gives 90 and 1min 30 gives 90.
  • duration raises on an empty string, an unknown unit, a negative value, any other text, or an argument that isn't a string.

santoku.random

santoku.random gives seeding, random strings and alphanumerics, and a clamped normal variate. Its fast seedable PRNG from C (fast_seed, fast_random, fast_max) helps when math.random is the bottleneck.

local random = require("santoku.random")
local str = require("santoku.string")
random.seed()
print("die roll:", random.num(1, 6))
print("string:", random.str(8))
print("alnum:", random.alnum(12))
print("normal-ish:", random.norm())
random.fast_seed(42)
print("fast:", random.fast_random())
print("fast max:", random.fast_max)
print("uniform:", random.fast_uniform())
print("normal:", random.fast_normal(0, 1))
print("hash_unit:", random.hash_unit(7, "user-42") == random.hash_unit(7, "user-42"))
print("token:", str.to_hex(random.bytes(16)))
Details
  • Requiring the module seeds both generators from process entropy, so distinct processes produce distinct streams without any setup.
  • Call seed or fast_seed with an explicit value only when you want a reproducible run.
  • alnum draws from the 62 ASCII alphanumerics. str draws from a raw byte range and includes punctuation.
  • The fast generator is one state per Lua state, shared by every C extension. So fast_seed also fixes C draws such as an unseeded vec:shuffle.
  • A C extension that includes <santoku/lua/utils.h> calls tk_fast_bind(L) in each entry point before tk_fast_random, tk_fast_normal or tk_fast_seed.
  • A draw before any bind aborts.
  • seed(n) fixes math.random draws such as arr.shuffle, and vec:shuffle(seed) seeds one call alone.
  • fast_uniform() draws from [0, 1), and fast_normal(mean, variance) draws a normal variate. Both use the fast generator.
  • hash_unit(seed, s) maps a seed and a string to a fixed number in (0, 1), the same on every run.
  • bytes(n) returns n bytes from the operating system's secure source (getrandom, arc4random or crypto.getRandomValues under wasm). Use it for keys, salts and tokens.
  • bytes raises "negative length" below zero.

santoku.async since santoku 5.0.0

require("santoku.async")(runtime) returns now, sleep, spawn, semaphore, latest, debounce, throttle, atleast and retry. The runtime supplies the scheduler. This page passes santoku.web.async, the browser runtime.

local async = require("santoku.async")(require("santoku.web.async"))
local t0 = async.now()
local double = async.atleast(function (x)
  return x * 2
end, 50)
print("atleast:", double(21), async.now() - t0 >= 50)
local tries = 0
local flaky = async.retry(function ()
  tries = tries + 1
  return tries == 3, tries
end, { times = 3, backoff = 10 })
print("retry:", flaky())
local search = async.latest(function (q)
  async.sleep(20)
  return "results for " .. q
end)
async.spawn(function ()
  print("never prints:", search("l"))
end)
print("latest:", search("lua"), search.busy())
local saved = {}
local save = async.debounce(function (text)
  saved[#saved + 1] = text
end, 30)
async.spawn(save, "l")
async.spawn(save, "lu")
save.cancel()
save("lua")
print("debounce:", #saved, saved[1])
return saved[1]
Details
  • A runtime is a table of now() in milliseconds, sleep(ms), spawn(fn, ...), scope(), run(s, fn, ...), kill(s) and semaphore(n). A scope has the fields parent, dead and running.
  • semaphore(n) returns wait(ms) and post(k). wait returns true, or false and "timeout". With no ms it waits until a post. post(k) wakes k waiters, one by default.
  • Each wrapper calls only the runtime functions it needs. retry needs only sleep.
RuntimeWorld
santoku.web.asyncthe browser
santoku.resty.asyncOpenResty and the resty CLI
santoku.system.asyncnative Lua: a poll() loop in santoku-system
  • On the native loop, a wait from the main thread runs the loop until the wait ends, so a plain script calls sleep or http.get as blocking calls. Tasks left when main returns are dropped, so join them with a semaphore.
  • Under PUC Lua 5.1, a task can't yield from inside a generic for iterator. Call sys.sh's iterator in a while loop inside a task.
  • An app keeps one module that builds santoku.async, such as return require("santoku.async")(require("santoku.web.async")). Every other module requires that one.
  • latest(fn) returns a callable with cancel() and busy(). A call kills the call before it, then runs fn in a new scope and returns fn's values.
  • The killed caller never resumes, so it needs no check for a cancelled result. cancel() kills the newest call, and busy() is true while it runs.
  • A call of a latest from inside its own fn raises "latest: this latest already runs on this coroutine".
  • debounce(fn, ms) calls fn after ms with no newer call. throttle(fn, ms) holds a call until ms have passed since fn last ran. In both, a newer call kills the waiting one.
  • Since santoku 5.1.0, debounce and throttle return a callable with cancel(). cancel() kills the waiting call, so fn never runs for it. A call already in fn keeps running.
  • spawn(fn, ...) runs any callable, so async.spawn(save, text) works on a debounce.
  • atleast(fn, ms) returns fn's values no sooner than ms after the call.
retry optionDefaultEffect
times3retries after the first attempt
backoff1000the first wait in milliseconds
multiplier3the growth of the wait after each retry
filterthe first value is falsyretries while it returns true for fn's values
  • retry makes times + 1 attempts and returns the last attempt's values unfiltered. Each wait is the backoff plus up to the backoff again of jitter.
  • atleast and retry return plain functions with fn's signature. Every wrapper takes fn's arguments and returns fn's values, so they compose: latest(atleast(get, 125)) or debounce(latest(get), 250).
  • atleast and retry keep no shared wait, so they have no cancel(). Wrap them in latest to cancel them.
  • santoku 5.0.0 removed the continuation-passing santoku.async: pipe, loop, race, events, each, map, filter, reduce, all, mapall, filterall and the i-prefixed iterator forms.

santoku.async.proxy since santoku 5.1.0

require("santoku.async.proxy")(channel) returns a table whose methods call an owner by name through channel.call. It needs no runtime.

local err = require("santoku.error")
local proxy = require("santoku.async.proxy")
local p = proxy({
  call = function (name, ...)
    if name == "add" then
      local a, b = ...
      return true, a + b
    end
    return nil, "failed: no method " .. name
  end,
})
print("add:", p.add(1, 2))
print("missing:", p.missing())
return err.checkok(p.add(20, 22))
Details
  • channel.call(name, ...) returns true and the method's results, or nil and "status: detail". A proxy method returns the same two forms.
  • err.checkok(p.add(1, 2)) returns the results or raises "status: detail". local ok, r = p.add(1, 2) branches on ok, and str.match(r, "^(%l+): ") gives the status word.
StatusMeans
fullthe channel had no room before its deadline
timeoutno result came before the deadline
lostthe owner died or stopped, so the call has no result
failedthe method raised, or its arguments or results couldn't cross
  • A channel that returns anything else raises "santoku.async.proxy: a channel call returns true and the results, or nil and \"status: detail\"".
  • A method that returns no values comes back as true alone.
  • santoku.web.sqlite.proxy builds its core on a santoku.web.rpc channel, and santoku.resty.sqlite builds a reader's write methods on a santoku.resty.ring channel.
  • The proxy caches each method caller, so p.add == p.add.

santoku.pack since santoku 5.1.0

pack(...) turns a list of Lua values into one string of bytes, and unpack(s) returns the same list, nils and the count included.

local err = require("santoku.error")
local pack = require("santoku.pack")
local s = pack.pack("id", nil, { 1, 2, x = true }, 1.5)
print("bytes:", #s)
local a, b, t, n = pack.unpack(s)
print("values:", a, b, t[2], t.x, n)
local ok, e = err.pcall(pack.pack, function () end)
print("function:", ok, e)
return #s
Details
  • It carries nil, booleans, numbers as 8-byte doubles, strings with embedded zeros, and plain tables nested up to 64 deep.
  • A userdata crosses when its metatable sets __pack to the name of the module that rebuilds it. pack stores that name and the string v:raw() returns. unpack requires the module and calls its from_raw with the string.
  • pack raises on a function, a thread, a table with a metatable, a table or userdata used as a key, and a userdata with no __pack. The userdata message says pack "takes Lua values only".
  • pack also raises on tables nested deeper than 64, which catches a cycle.
  • unpack raises on truncated input, an unknown tag and trailing bytes.
BytesValue
a varint countthe number of values
tag 0, 1, 2nil, false, true
tag 3, then 8 bytesa number
tag 4, a varint length, the bytesa string
tag 5, a varint pair count, then key and value per paira table
tag 6, a varint length and the module name, then a varint length and the raw stringa userdata with __pack
  • C code includes santoku/pack.h and calls tk_pack_measure, tk_pack_write and tk_unpack to pack into its own buffer.
  • santoku.resty.ring and santoku.web.rpc carry calls in this format.

santoku.serialize

Calling santoku.serialize serializes any value, tables included, to Lua source that round-trips through santoku.lua's loadstring.

local serialize = require("santoku.serialize")
local lua = require("santoku.lua")
local src = serialize({
  name = "example",
  tags = { "lua", "pwa" },
  nested = { deep = true },
})
print(src)
local restored = lua.loadstring("return " .. src)()
print("round trip:", restored.name, restored.tags[2])
return restored.name
Details
  • Requiring santoku.autoserialize patches the global print, so every printed table shows its contents instead of an address.
  • toku lua --serialize loads santoku.autoserialize for you.
  • This page runs each example with its own print, so the patch is shown for reading only.

santoku.lua and santoku.profile

santoku.lua owns what the stdlib's loadstring and setfenv do. santoku.profile times labelled code once enable() is called.

local lua = require("santoku.lua")
local err = require("santoku.error")
local profile = require("santoku.profile")
print("env:", lua.loadstring("return x * 2", { x = 21 })())
print(err.pcall(lua.loadstring, "return +", nil, "=snippet"))
local u = lua.userdata({ __index = function (_, k) return k .. "!" end })
print("userdata:", type(u), u.hi)
lua.checkkeys({ size = 10, mode = "fast" }, "opts", { "size", "mode" })
lua.checkkeys(nil, "opts", { "size", "mode" })
print(err.pcall(lua.checkkeys, { size = 10, sise = 1 }, "opts", { "size", "mode" }))
print(err.pcall(lua.checkkeys, 5, "opts", { "size" }))
profile.enable()
local sum = profile.wrapped("sum", function (n)
  local s = 0
  for i = 1, n do
    s = s + i
  end
  return s
end)
local close = profile.span("three sums")
for _ = 1, 3 do
  sum(1000)
end
close()
for _, r in ipairs(profile.report()) do
  print(r.label, r.calls)
end
profile.disable()
return sum(10)
Details
  • loadstring(code, env, name) compiles code and sets env as its environment when given. It raises the compile error where the stdlib returns nil.
  • userdata(mt) returns an empty userdata carrying mt, which is how a plain Lua value gets a __gc.
  • gc_charge(bytes) tells the collector about memory a C module allocated outside it. It runs one collector step per KiB.
  • malloc_trim() returns freed heap to the system on glibc.
  • checkkeys(t, name, keys), since santoku 3.4.0, checks an options table against a list of allowed string keys.
  • For checkkeys, nil passes. A value that isn't a table raises name, "value is not of type" and "table".
  • Any other key raises name and "unknown option <key>". A numeric key shows as its number, and a boolean or table key as its type name.
  • keys must hold only strings.
  • C modules call the same check as tk_lua_checkkeys in santoku/lua/utils.h.
  • While santoku.profile is disabled, each wrapper is a plain call.
  • wrapped(label, fn) and wrap(t, names, prefix) wrap functions. span(label) returns a closer, and timed(label, fn, ...) times one call.
  • report() lists { label, calls, total, self, mean, min, max } in seconds, sorted by self time. format() renders the report in milliseconds.
  • Requiring santoku.trace prints every executed line of file-backed code until the state closes.
  • santoku.tracer() starts the same hook and returns a stop function.

co, inherit, geo and env

santoku.co builds tagged coroutine sets that nest without stealing each other's yields. inherit manages __index chains, geo does planar and great-circle math, and env reads variables.

local inherit = require("santoku.inherit")
local base = { greet = function () return "hello" end }
local child = inherit.pushindex({}, base)
print("inherited:", child.greet())
local geo = require("santoku.geo")
local tampa = { lat = 27.95, lon = -82.46 }
local albany = { lat = 42.65, lon = -73.75 }
print("km apart:", geo.earth_distance(tampa, albany))
print("angle:", geo.angle({ x = 0, y = 0 }, { x = 1, y = 1 }))
local env = require("santoku.env")
print("editor:", env.var("EDITOR", "vi"))
print("optional:", env.var("SANTOKU_UNSET_EXAMPLE", nil))
local err = require("santoku.error")
print("required:", err.pcall(env.var, "SANTOKU_UNSET_EXAMPLE"))
local co = require("santoku.co")()
local gen = co.wrap(function ()
  co.yield(1)
  co.yield(2)
end)
print("yields:", gen(), gen())
local owner = co.thread()
local inner = co.inner(function ()
  return co.thread() == owner
end)
print("inner shares the thread:", co.resume(inner))
Details
  • Since santoku 5.0.0, co.inner(f) creates a coroutine that counts as its creator's thread, and co.thread() returns the logical thread: the creator of an inner coroutine, or the running coroutine.
  • err.pcall runs fn in an inner coroutine, so a runtime that checks co.thread() still finds its task inside the pcall.
  • env.var(name, default) returns the default when the variable is unset, and an explicit nil default returns nil.
  • With no default, env.var raises Missing environment variable: name.
  • Under err.pcall, env.var returns false, Missing environment variable and the name.
  • env.with_paths(path, cpath, fn, ...) runs fn with package.path and package.cpath swapped. It restores both even when fn raises.
  • env.path() and env.cpath() read the current values.
  • bench and test cover timing and test scripts.

Examples

Projects that toku init creates with this rock. The examples page shows their files.

  • A library with a command: A Lua rock with a C module, a sqlite store behind migrations, and an argparse command. toku init --example lib my-lib