Host API
The host API is what a package’s Lua can call beyond plain Lua. That is the globals and tables on this page and the shared library’s modules.
The functions that change state (emit, store, queue and report) are listed under effects.
The sandbox
Section titled “The sandbox”Packages run in sandboxed Luau. There is no io, os or package library. debug.info does not take the f option.
A package declares the host API version it is written for in host_api. This version of Hour Advantage runs 1 and 2 (host API versions).
Each call sees the package exactly as it was loaded. Nothing carries over between calls except through store:
- Module-level code runs when the package loads, not once per call. Compute nothing at load that depends on the time, or on vars and secrets.
- Tables built at load are read-only during calls. Copy one before changing it (
tables.copy). - Keep state in
store. Never keep it in a global or a module-level variable a handler assigns.
Each call is limited to 500 ms and 32 MB of memory. Tables nested deeper than 64 levels cannot be converted to JSON.
A mistake raises an error. For example, a bad option, an unknown zone or encoding, or a value that does not fit. Some functions read device text, where “not this” is an ordinary answer. These return nil instead, as noted. Strings are binary-safe throughout.
Helpers
Section titled “Helpers”| Helper | |
|---|---|
trim(s) | s without surrounding whitespace. "" for nil. |
split(s, sep) | Plain split keeping empty fields. split("a,,b", ",") is { "a", "", "b" }. |
split_lines(s) | Lines. A trailing \r is dropped. Empty lines are left out. |
parse_key_value(s, pair_sep, kv_sep?) | parse_key_value("A=1,B=2", ",") is { A = "1", B = "2" }. Each pair is split on its first kv_sep ("=" when not given). Keys are trimmed. Values are as sent. |
to_int(s, default?) | Decimal text or a number, truncated toward zero. Otherwise default (or 0). |
to_float(s, default?) | Decimal text or a number. Otherwise default (or 0). |
starts_with(s, prefix), ends_with(s, suffix), contains(s, needle) | Plain text tests. False for nil. |
remove_prefix(s, prefix) | s without prefix, when it starts with it. |
replace(s, old, new) | Every occurrence of old, as plain text. |
pad_left(s, width, ch?), pad_right(s, width, ch?) | Padded to width with ch (default a space). |
field(v, default?) | A value as text. Nil or "" gives default (or ""). Booleans give "1"/"0". Numbers and strings give themselves. Anything else raises. |
allow_biometrics(ctx, user_id) | False for a user id in ctx.biometrics_refused. Do not ask the device for that person’s templates or photos (biometrics). The gateway drops them whatever the package does. |
json.encode(v), json.decode(s), json.array(t?) | JSON. decode raises on text that is not JSON. Read device input with pcall(json.decode, body). An empty table encodes as {}. json.array() (or a list read from JSON) encodes as []. |
base64.encode(s), base64.decode(s) | Standard base64, binary-safe. |
log.info(msg), log.warn(msg), log.error(msg) | A line in the gateway’s log, and in hourd dev and replay beside the exchange. A line is cut to 4096 bytes, with the number cut said. A package may write 100 lines at once and 50 a second after that. Lines over it are left out of the log. The next line written says how many were left out. hourd dev and replay show every line, whole (a package’s log lines). |
vars.get(name), secrets.get(name) | The tenant’s vars and secrets (environments): text, or nil. A value set for the package wins over the tenant’s of the same name. Another package’s is never seen. Readable in any package function, not while the package loads. Never put a secret in an event, a log line or an error. |
require(name) | A module of the package, its vendor folders or the shared library. |
Text that is not valid UTF-8 is converted with replacement characters when it leaves Lua in an event or report. For example, device data in a legacy encoding is not valid UTF-8. Convert it first with text.decode.
“Now” is the gateway’s clock, never read from the host directly. A scenario runs at one fixed instant, and packages see that instant too.
Zone rules come from the time zone database built into the gateway. The host’s zone is never used.
tz is a zone name ("America/Chicago") or a fixed offset ("-05:00").
time.now(tz?):{ local, offset, standard_offset, utc, unix }intz, or UTC.localis"YYYY-MM-DDTHH:MM:SS".time.at(tz, "2026-10-01 08:00:00"): places a wall-clock time in a zone. A space orTgoes between date and time. It returns{ local, offset, time, utc, ambiguous, time_zone, zoned }, or nil when the text is not such a time. It raises withouttz.ambiguousis true when the zone shows that time twice (daylight saving ending) or never (starting).- A time shown twice is taken as the first. Its
offsetis the one in force before the change. - A skipped time is placed forward over the gap. For example, 02:30 reads 03:30 when clocks skip 02:00 to 03:00.
localis the text as given.time_zoneis the zone name, or the offset whentzis one.zonedistimefollowed by[time_zone](RFC 9557).
time.dst(tz, year?): the zone’s daylight-saving changes in a year (default: this year), or nil when it has none. It returns{ starts, ends, saving_minutes }. Each change is the wall-clock moment just before it. A change has these fields:month,day,hour,minute,weekday(0 = Sunday),week,lastandlocal.weekis which occurrence of that weekday in the month, 1 to 5.lastis the month’s last such weekday.
A value below is unix seconds, time text (RFC 3339, RFC 9557 or "YYYY-MM-DD HH:MM:SS"), a table a time function returned, or nil for now. Instants are shown in tz (UTC without one). Wall-clock times are placed in tz as time.at places them, and raise without one. Placed results are time.at’s table plus unix.
time.parse(text, format, tz?): strftime-style. It is placed when the text has an offset or zone, ortzis given. Otherwise it is civil{ local, year, month, day, hour, minute, second }. It is nil when the text does not match.time.format(value, format, tz?): strftime-style text.time.from_epoch(n, opts?, tz?),time.to_epoch(value, opts?, tz?): counts from a base.optstakes these:unitis"s"(default) or"ms".baseis a year (default 1970) or"YYYY-MM-DD".wall = trueis for when the count is wall-clock time, as most clocks keep it.
time.bcd_decode(bytes, layout?),time.bcd_encode(value, layout?, tz?): one BCD byte per field ofYYYY YY MM DD hh mm ss ww xx.YYYYis two bytes. The default layout is"YYMMDDhhmmss".time.add(value, delta, tz?): calendar arithmetic in the zone, withdeltaofyears,months,weeks,days,hours,minutes,seconds.time.weekday(value, tz?): 0 = Sunday.time.day_bounds(value, tz?),time.week_bounds(value, tz?, first_weekday?):{ start, ["end"] }. These are the local day’s (week’s) first instant and the next one’s. A week starts on Monday by default. A daylight-saving day is 23 or 25 hours long.time.minutes_between(a, b, tz?): whole minutes fromatob.time.hhmm_to_minutes("08:30")is 510. It gives nil for other text. Hours may pass 23, and-negates.time.minutes_to_hhmm(510)is"08:30".time.duration_parse("PT8H30M")is 30600 (seconds). It gives nil for other text, or for years and months.time.duration_format(30600)is"PT8H30M".
local tz = ctx.options.timezonelocal t = time.from_epoch(bytes.read(req.body, 5, "u32le"), { base = 2000, wall = true }, tz)local today = time.day_bounds(nil, tz)local stamp = time.bcd_encode(nil, "YYMMDDhhmmss", tz)Offsets are 1-based, as in string.sub. The integer kinds are "u8" and "i8". The others are "u16", "i16", "u32", "i32", "u64" and "i64", followed by le or be. A 64-bit value past 2^53 does not fit a Lua number and raises.
bytes.to_hex(s),bytes.from_hex(hex): lowercase hex.from_hexskips spaces, tabs, line breaks,:and-between digits.bytes.read(s, offset, kind),bytes.write(s, offset, kind, value): an integer at an offset.writereturns the new string (#s + 1appends).bytes.crc16(s, variant?)("modbus", the default,"ccitt-false"or"xmodem"),bytes.crc32(s),bytes.sum8(s),bytes.sum16(s),bytes.xor8(s): checksums as numbers.bytes.bit(n, i),bytes.set_bit(n, i, on?): flag bits, 0 the least significant, up to 52.bytes.frames(s, { size = 2, endian = "be", inclusive = false }): the whole length-prefixed frames (without their prefix) and the leftover, a frame still arriving.sizeis 1, 2 or 4.inclusiveis for when the length counts the prefix itself.
local buffered = (store.get("partial") or "") .. req.bodylocal frames, rest = bytes.frames(buffered, { size = 2, endian = "le" })store.set("partial", rest)for _, f in ipairs(frames) do local crc = bytes.read(f, #f - 1, "u16le") if crc ~= bytes.crc16(string.sub(f, 1, -3)) then log.warn("bad frame") endendThe encodings are gbk, gb2312, gb18030, big5, shift_jis, windows-1252, iso-8859-1 (true Latin-1), utf-16le, utf-16be and utf-8, in any case.
text.decode(s, encoding): the text as UTF-8, and whether anything did not decode (it reads U+FFFD).text.encode(s, encoding): the bytes, and whether a character could not be held (it becomes?).text.truncate(s, n): at mostnbytes, never splitting a UTF-8 character.text.ascii(s): transliterated to ASCII ("José"is"Jose"), for displays that show nothing else.
local name = text.decode(raw_name, "gbk")local out = text.encode(text.truncate(user.name, 24), "gbk")The global text table is the host’s. The shared library’s text helpers are a module. local text_lib = require("text") names it apart.
xml, multipart, url, query, csv
Section titled “xml, multipart, url, query, csv”xml.decode(text):{ root = value }.- An element with neither attributes nor child elements is its text (
""when empty). - Any other element is a table. It has
["@attr"]attributes, children by name, and its own text as["#text"]. When a name repeats, its children are an array, in document order. - Prefixes are kept as written (
["s:Body"]). - Comments and processing instructions are dropped. CDATA is text.
- It raises on text that is not well-formed UTF-8 XML.
- An element with neither attributes nor child elements is its text (
xml.encode(doc, { declaration = true }): the inverse. It writes attributes, then#text, then children sorted by name.["#children"] = { { a = 1 }, { b = 2 } }writes children in that order.multipart.parse(body, content_type): the parts, each{ name, filename, content_type, body }. It raises when the content type has no boundary or the body is malformed.url.encode(s),url.decode(s): percent-encoding. RFC 3986 unreserved characters are kept, and+is not a space.query.parse(s):values, pairs. These are the first value of each name, and every{ name, value }in order (+is a space).query.build(t): form-encoded, names sorted. A list value repeats its name.csv.parse(text, { sep = ",", quote = '"', header = true, trim = false }): quote-aware rows. They are keyed by the header’s names, or arrays of fields without a header.
local doc = xml.decode('<Event id="7"><Card>123</Card><Card>456</Card></Event>')-- doc.Event["@id"] == "7"; doc.Event.Card == { "123", "456" }for _, part in ipairs(multipart.parse(req.body, req.headers["content-type"])) do if part.filename then photo = part.body endendfor _, row in ipairs(csv.parse(body, { sep = "\t" })) do log.info(row.PIN) endJPEG, PNG and BMP. A photo over 16384 pixels a side or 40 megapixels is refused. The work counts against the call’s time limit.
image.info(data):{ format, width, height, bytes }. It raises on anything else.image.fit(data, { max_width, max_height, max_bytes, format = "jpeg", quality = 85 }): the photo is scaled down (keeping its shape), informat. It is recompressed or scaled further, not below 16 pixels a side, until it is at mostmax_bytes. It returns the data and its info. A photo that already fits in that format is returned unchanged. It raises when it cannot fit.
local jpeg, info = image.fit(part.body, { max_width = 480, max_height = 640, max_bytes = 30000 })crypto, http, uuid
Section titled “crypto, http, uuid”crypto.sha256(s),crypto.sha1(s),crypto.md5(s): lowercase hex.crypto.hmac_sha256(key, s),crypto.hmac_sha1(key, s): lowercase hex.crypto.equals(a, b): equal, in time that does not depend on where they differ. Compare signatures with it.crypto.random_bytes(n):n(0 to 65536) bytes from the operating system’s random source.http.digest_auth(challenge, method, uri, user, password, { nc = 1, cnonce = nil }): the Authorization header answering aWWW-AuthenticateDigest challenge. It follows RFC 7616. That covers MD5, SHA-256 and their-sessforms, qopauthor none, and a random cnonce unless given. It raises when the challenge has no Digest challenge it supports.uuid.v4(): a random UUID, lowercase and hyphenated.
local auth = http.digest_auth(challenge, "GET", "/cgi-bin/users", "admin", secrets.get("acme_password"))Shared library
Section titled “Shared library”These are modules for what many protocols have in common. They are built into Hour Advantage. A package requires them without carrying them, and a bundle holds none of them. Editor types for each are in _types/lib.
An error raised inside a library function names the function and the package line that called it:
loading package [email protected]: [string "zk"]:845: template.define: unknown placeholder {pin:hex}template
Section titled “template”Text commands from {placeholder} templates, for devices that take commands as delimited text.
Every value is refused if it holds a control character. A tab or line break inside a value (an employee’s name) would add fields or whole commands. Never concatenate a parameter into a delimited command yourself.
| Placeholder | |
|---|---|
{name} | A required value. |
{name|x} | Optional, x when not given (empty when x is left out). |
{name:b64} | Base64 text, padded to a multiple of 4. |
{name:b64len} | The length of that padded base64 text. |
{name:bool} | true/1 as 1, anything else 0. |
{name:hhmm} | "8:30" or "08:30" as 0830. |
-
template.define(commands, key, title, tpl, extra?): adds the commandkeytocommands, built fromtpl. Its parameters are inferred from the template:b64andb64lenare binary.boolis boolean.hhmmis text with the patterntemplate.HHMM.- Anything else is text.
- A parameter is required unless it has a default.
extracarries the command’s other fields (description,writes,implements,internal,quick,success,sensitive_result,sensitive) andparams.paramsare typed declarations that replace the inferred ones by name. A declared parameter not in the template, or a key defined twice, raises. -
template.render(tpl, p): the template withp’s values in it. -
template.params(tpl): the parameters a template takes, asdefineinfers them. -
template.value(name, v, default?): a value as text (asfield), refusing control characters. -
template.hhmm(name, v):"8:30"or"08:30"as"0830". -
template.HHMM: the pattern a time-of-day parameter is declared with.
local template = require("template")template.define(M.commands, "add_user", "Add user", "USER ADD id={user_id}\tname={name|}\tadmin={admin:bool}", { writes = { "people" }, params = { { name = "user_id", type = "string", required = true, pattern = "^[0-9]{1,9}$" } },})-- build({ user_id = "7", name = "Ann", admin = true }) gives "USER ADD id=7\tname=Ann\tadmin=1"commands
Section titled “commands”commands.step(action, params?):{ action, params }, one step.commands.gate(action, params?): a step withgate = true.commands.set_param(command, decl): replaces the command’s declaration of the parameterdecl.name. It raises when the command has none.commands.check(command, rules): wraps the command’sbuildso each given value (not nil or"") runs through its rule first. A rule isfunction(name, value)returning the text to send (seeparams).commands.flags(command, names):true/falsegiven for these parameters reachbuildas"1"/"0".commands.days_param(name, description): alistparameter of days of the week ("mon,tue", any case), at most 7.
local commands = require("commands")local params = require("params")commands.check(M.commands.set_volume, { level = params.whole(0, 100) })params
Section titled “params”These are for a command’s build. They put a value into the form a device takes, and refuse what a declaration cannot say. A refusal names the parameter: parameter 'level' must be a whole number from 0 to 100.
params.refuse(name, what): raisesparameter '<name>' must be <what>.params.list(v): a list as it is, or text split on commas (items trimmed).{}for nil or"".params.whole(lo, hi?): a rule, a whole number fromlotohi(no upper limit when nil), as text.params.one_of(values): a rule, one ofvalues, as text.params.yes_no(name, v, default?):true/false,1/0,"true"/"false"as"1"/"0".defaultwhen not given.params.ids(name, v, most, lo, hi): a list of at mostmostwhole numbers fromlotohi.params.date_time(name, v, end_of_day?):"2026-10-01","2026-10-01 08:30"or"2026-10-01 08:30:00"(or withT) as{ date = "2026-10-01", time = "08:30:00" }. A date alone is midnight, or withend_of_day23:59:59.params.hh_mm(name, v):"8:30"or"08:30"as"08:30".params.days(name, v): the days a list names, as a set ({ mon = true }).params.DAYS:{ "sun", "mon", "tue", "wed", "thu", "fri", "sat" }.
local params = require("params")local from = params.date_time("from", p.from) -- { date = "2026-10-01", time = "00:00:00" }local to = params.date_time("to", p.to, true) -- a date alone ends at 23:59:59local on = params.days("days", p.days) -- { mon = true, tue = true }uploads
Section titled “uploads”uploads.cursors(): the saved cursors, by table name.uploads.save_cursor(name, value): saves a table’s cursor. It does nothing whenvalueis nil or"".uploads.set_cursor(name, value): sets a table’s cursor, or clears it whenvalueis nil, so the device sends from the start. It is for a package that finds a cursor it must not hand back. The ZK packages do for a stamp ahead of the present.uploads.unparsed(table_name, line, reason): emits the row as anunparsedevent (reason,raw,context.table), keyed on the table and line. A line over 16 KiB reaches sinks as its start and a hash (theunparsedschema). Emit the line as it is.
The cursors are kept in store under the key stamps. Use another key for your own state.
local uploads = require("uploads")local since = uploads.cursors()["ATTLOG"] or "0"-- ... emit each row; one that cannot be read:uploads.unparsed("ATTLOG", line, "no user id")uploads.save_cursor("ATTLOG", req.query.Stamp)dates.local_now(tz?): the wall-clock time now intz,"YYYY-MM-DD HH:MM:SS".dates.add_days(date, n):"YYYY-MM-DD"ndays later (earlier whennis negative). Anything after the date is ignored.dates.rfc3339(ts, tz?): an RFC 3339 timestamp placed in the offset it carries (Zis +00:00), or intzwhen it carries none, astime.atplaces it. Fractions of a second are dropped. Nil when it cannot be read, or carries no offset and there is notz.
local dates = require("dates")dates.add_days("2026-02-27", 2) -- "2026-03-01"local at = dates.rfc3339(p.ts, ctx.options.timezone) -- time.at's table, or niltext (module)
Section titled “text (module)”text.blank(s):sis nil or"".text.split_once(s, sep): the text before the firstsep(plain, not a pattern) and after it.sand nil when there is none.text.key_value_list(s):"Key=value"pairs separated by commas or line breaks, as a table. Keys are trimmed and values kept as sent. A piece without=belongs to the value before it ("Vendor=Example Co., Ltd.").text.major_version(v): the leading whole number of a version ("12.0"is"12"). Nil when there is none or it is 0.
local text_lib = require("text")local tag, rest = text_lib.split_once("USER PIN=1", " ") -- "USER", "PIN=1"local info = text_lib.key_value_list("~DeviceName=X1,FWVersion=Ver 6.6")tables
Section titled “tables”tables.copy(t): a shallow copy ({}for nil).tables.merged(base, extra): a copy ofbasewithextra’s keys set over it.tables.append(list, more):listwithmore’s items added. It returnslist.tables.has(list, value): whetherlistholdsvalue.tables.get(t, key, default):t[key], ordefaultwhen it is nil (falsestaysfalse).
local tables = require("tables")local p = tables.merged({ role = "user" }, given)Card numbers are canonical text. That is decimal digits without leading zeros ("0" for zero), exact past 2^53. A card given as a Lua number must be a whole number of at most 2^53. Every function but from_wiegand raises for a value it cannot take.
cards.normalize(card): the canonical number of a whole number, decimal text ("00123"), hex text after0x("0x7B"), or a standard card{ number, format?, facility? }. A card with a facility (formatw26orw34) is its data bits. Those are the facility, then the number, without parity.cards.decimal(value, digits?): decimal text, zero-padded todigits.cards.hex(value, digits?): upper-case hex without0x, zero-padded.cards.from_hex(hex): hex text (0xoptional) as the canonical number.cards.reverse_bytes(value, width): the number with itswidthbytes in reverse order.cards.wiegand(format, facility, number): the whole Wiegand frame, parity bits included.cards.from_wiegand(format, frame): the facility and number of a frame. Nil and why when it is not one (too wide, parity wrong).cards.WIEGAND: the formats,w26(8-bit facility, 16-bit number) andw34(16 and 16).
local cards = require("cards")cards.normalize("0x7B") -- "123"cards.normalize({ number = "4567", facility = "123", format = "w26" }) -- "8065495"cards.hex(255, 4) -- "00FF"cards.reverse_bytes(305419896, 4) -- "2018915346"cards.wiegand("w26", 123, 4567) -- "49685422"cards.from_wiegand("w26", "49685423") -- nil, "odd parity bit is wrong"