LuaJIT standard library#

Every name a checked program can use without declaring it, and every module LuaJIT loads by name, as the compiler itself declares them. nupp reads these files to decide what a call means, so a signature here is the signature the checker enforces.

Globals#

The functions and values a program can name anywhere. Their declarations are loaded before any source is checked, so nothing requires them and nothing can shadow them by accident.

assert function#

local assert: function<T>(takes v: T?, msg: any?): T preserves v

Raises msg when v is nil or false, and otherwise returns v.

Type parameters#

Name Description
T the asserted type

Arguments#

Name Type Description
takes v T? the value to test
msg any? the error to raise, "assertion failed!" by default

Returns#

Type Description
T preserves v v, now known not to be nil or false

collectgarbage function#

local collectgarbage: function(): number
& function(opt: 'collect' | 'stop' | 'restart' | 'count' | 'setpause' | 'setstepmul', arg: number?): number
& function(opt: 'step' | 'isrunning', arg: number?): boolean

Controls the garbage collector. opt is "collect" for a full cycle, the default, or "stop", "restart", "count", "step", "setpause", "setstepmul" or "isrunning".

Arguments#

Name Type Description
opt `'collect' 'stop'
arg number? the step size or parameter that the operation takes

Returns#

Type Description
number what the operation reports: "count" gives the kilobytes in use, while "step" and "isrunning" answer a boolean

dofile function#

local dofile: function(path: string?): any

Loads and runs the file at path, or standard input when it is omitted. Errors from the chunk propagate to the caller.

Arguments#

Name Type Description
path string? the file to run, or nil for standard input

Returns#

Type Description
any whatever the chunk returns

error function#

local error: nosuspend function(msg: any, level: number?): never

Raises msg as an error, unwinding to the nearest pcall. A string message is prefixed with a source position chosen by level: 1, the default, blames the caller of error, 2 blames its caller in turn, and 0 adds no position at all.

Arguments#

Name Type Description
msg any the error value to raise
level number? whose position to blame, or 0 for none

Returns#

Type Description
never

gcinfo function#

local gcinfo: function(): integer

Returns the amount of memory in use, in kilobytes. Superseded by collectgarbage("count").

Returns#

Type Description
integer the kilobytes currently allocated

getfenv function#

local getfenv: function(f: any?): table

Returns the environment a function sees as its globals, addressed the way setfenv addresses one.

Arguments#

Name Type Description
f any? the function to ask about, or a stack level

Returns#

Type Description
table that function's globals

getmetatable function#

local getmetatable: function<T>(v: T): metatable<T>?

Returns the metatable of v, or the value of its __metatable field when it has one, or nil when there is no metatable.

Type parameters#

Name Description
T

Arguments#

Name Type Description
v T the value to inspect

Returns#

Type Description
metatable\<T\>? the metatable, its __metatable stand-in, or nil

ipairs function#

const ipairs: nosuspend function<V>(borrows t: const{V}): nosuspend function(): (integer, V) borrows (t)

Returns an iterator over the array part of t, from index 1 up to the first missing element.

Type parameters#

Name Description
V the element type

Arguments#

Name Type Description
borrows t const{V} the array to traverse

Returns#

Type Description
nosuspend function(): (integer, V) borrows (t) an iterator yielding each index and the element stored there

load function#

local load: function(chunk: any, name: string?, mode: string?, env: table?): (any, string?)

Compiles a chunk read piecewise from chunk, a function returning successive pieces of source, without running it.

Arguments#

Name Type Description
chunk any the reader function, or the source string
name string? the chunk name to use in error messages
mode string? "b", "t" or "bt", limiting binary or text sources
env table? the environment the chunk sees as its globals

Returns#

Type Description
any the compiled chunk, or nil when it does not compile
string? the compile error, when there was one

loadfile function#

local loadfile: function(path: string?, mode: string?, env: table?): (any, string?)

Compiles the file at path, or standard input when it is omitted, without running it.

Arguments#

Name Type Description
path string? the file to compile, or nil for standard input
mode string? "b", "t" or "bt", limiting binary or text sources
env table? the environment the chunk sees as its globals

Returns#

Type Description
any the compiled chunk, or nil when it does not load
string? the load error, when there was one

loadstring function#

local loadstring: function(s: string, name: string?): (any, string?)

Compiles the string s as a chunk, without running it.

Arguments#

Name Type Description
s string the source to compile
name string? the chunk name to use in error messages

Returns#

Type Description
any the compiled chunk, or nil when it does not compile
string? the compile error, when there was one

newproxy constructor#

local newproxy: function(mt: any?): userdata

Creates a userdata with a fresh empty metatable, with no metatable, or sharing the metatable of an existing proxy.

Arguments#

Name Type Description
mt any? true for a new metatable, false or nil for none, or a proxy to share a metatable with

Returns#

Type Description
userdata the new userdata

next function#

local next: nosuspend function(t: table, k: any?): (any, any)

Returns the pair that follows key k in t. Passing nil, or omitting k, returns the first pair; the traversal order is unspecified.

Arguments#

Name Type Description
t table the table to step through
k any? the key to step past, or nil to start the traversal

Returns#

Type Description
any the next key, or nil once the traversal is done
any the value stored at that key

pairs function#

local pairs: nosuspend function<K, V>(t: {readonly [K]: V}): nosuspend function(): (K, V)

Returns an iterator over every key/value pair of t, in unspecified order. New keys must not be added to t during the traversal.

Type parameters#

Name Description
K the key type
V the value type

Arguments#

Name Type Description
t {readonly \[K\]: V} the table to traverse

Returns#

Type Description
nosuspend function(): (K, V) an iterator yielding each key and its value, and nil when done

pcall function#

local pcall: function<A..., R...>(scoped f: function(A...): R..., A...): ((true, R...) | (false, unknown))
& function<A..., R...>(takes f: function(A...): R..., A...): ((true, R...) | (false, unknown))

Calls f with the given arguments, trapping any error it raises.

so has to be narrowed or cast before it is used as anything in particular

Type parameters#

Name Description
A
R

Arguments#

Name Type Description
scoped f function(A...): R... the function to call
? A...

local print: nosuspend function(borrows ...: any)

Writes every argument to standard output, converted with tostring, separated by tabs and followed by a newline.

Arguments#

Name Type Description
borrows ? any

rawequal function#

local rawequal: nosuspend function(borrows a: any, borrows b: any): boolean

Compares two values for primitive equality, without an __eq metamethod.

Arguments#

Name Type Description
borrows a any the left value
borrows b any the right value

Returns#

Type Description
boolean whether the values are primitively equal

rawget function#

local rawget: nosuspend function(t: table, k: any): any

Reads t[k] without consulting an __index metamethod.

Arguments#

Name Type Description
t table the table to read
k any the key to read

Returns#

Type Description
any the stored value, or nil when the key is absent

rawlen function#

local rawlen: nosuspend function(borrows v: any): integer

Returns the length of a table or string without consulting a __len metamethod.

Arguments#

Name Type Description
borrows v any the table or string to measure

Returns#

Type Description
integer the length

rawset function#

local rawset: nosuspend function(t: table, k: any, v: any): table

Assigns t[k] = v without consulting a __newindex metamethod.

Arguments#

Name Type Description
t table the table to write to
k any the key to write
v any the value to store

Returns#

Type Description
table t

require function#

local require: function(name: string): any

Loads module name the first time it is asked for and returns its value. Later calls hand back the value cached in package.loaded.

A call through the unshadowed builtin with a literal name is resolved by the checker to the module's declared type, and one with a computed name answers unknown in a strict file. The any declared here is what a gradual file gets for a computed name, and what any call through a shadowing binding gets.

Arguments#

Name Type Description
name string the module name, with . separating path components

Returns#

Type Description
any the value the module returned

select function#

local select: function<A...>(n: '#', A...): integer & function<A...>(n: number, A...): A...

Selects from a vararg list. With a number, returns every argument from the nth onwards, counting from the end when n is negative; with "#", returns how many arguments follow.

Type parameters#

Name Description
A

Arguments#

Name Type Description
n '#' the 1-based index to select from, or the string "#"
? A...

Returns#

Type Description
integer the selected arguments, or their count

setfenv function#

local setfenv: function(f: any, env: table): any

Sets the environment a function sees as its globals. f is the function itself, or a stack level: 1 is the caller, 0 the running thread.

Arguments#

Name Type Description
f any the function whose globals are being replaced, or a stack level
env table the table to use as that function's globals

Returns#

Type Description
any f, when it was a function

setmetatable function#

local setmetatable: function<T>(takes t: T, mt: metatable<T>?): T preserves t

Sets t's metatable, or removes it when mt is nil. Raises when the current metatable has a __metatable field.

Type parameters#

Name Description
T the table type

Arguments#

Name Type Description
takes t T the table to change
mt metatable\<T\>? the new metatable, or nil to remove the current one

Returns#

Type Description
T preserves t t

tonumber function#

local tonumber: nosuspend function(v: any, base: number?): number?

Converts a value to a number, or nil when it has no numeric meaning. With base, v is read as an unsigned integer numeral in that base.

Arguments#

Name Type Description
v any the value to convert
base number? the numeral base, 2 through 36; decimal when omitted

Returns#

Type Description
number? the number, or nil when v does not denote one

tostring function#

local tostring: nosuspend function(borrows v: any): string

Converts a value to a string, honoring a __tostring metamethod.

Arguments#

Name Type Description
borrows v any the value to convert

Returns#

Type Description
string the string form of v

type function#

local type: nosuspend function(borrows v: any): ("nil"
| "boolean"
| "number"
| "string"
| "table"
| "function"
| "thread"
| "userdata"
| "cdata")

Returns the type name of a value: "nil", "boolean", "number", "string", "table", "function", "thread" or "userdata", plus "cdata" for FFI values.

The result is the closed set of those names rather than string, so a comparison against one of them narrows, a chain over all of them is exhaustive, and a comparison against a name LuaJIT never returns is caught where it is written.

Arguments#

Name Type Description
borrows v any the value to classify

Returns#

Type Description
`"nil"
"boolean"
"number"
"string"
"table"
"function"
"thread"
"userdata"
"cdata"` the type name

unpack function#

local unpack: function<T>(t: const{T}, i: number?, j: number?): ...T

Returns the elements of t from index i through j as separate values.

Type parameters#

Name Description
T

Arguments#

Name Type Description
t const{T} the array to expand
i number? the first index, 1 by default
j number? the last index, #t by default

xpcall function#

local xpcall: function<E, A..., R...>(
    scoped f: function(A...): R...,
    scoped handler: function(any): E,
    A...
): ((true, R...) | (false, E))
    & function<E, A..., R...>(
    takes f: function(A...): R...,
    scoped handler: function(any): E,
    A...
): ((true, R...) | (false, E))

Like pcall, but runs handler on the error before the stack unwinds, so it can still collect a traceback.

Type parameters#

Name Description
E
A
R

Arguments#

Name Type Description
scoped f function(A...): R... the function to call
scoped handler function(any): E called with the error value at the point of the failure
? A...

arg variable#

local arg: {string}

The command-line arguments of the running script, where arg[1] is the first one. Index 0 holds the script name, and negative indices hold the interpreter and the options it was given.

string#

String manipulation and pattern matching. Every function here is also reachable as a method on a string value, so s:upper() means string.upper(s).

string.byte function#

local byte: nosuspend function(s: string, i: number?, j: number?): ...integer

Returns the numeric codes of the characters of s from i to j.

Arguments#

Name Type Description
s string the string to read
i number? the first index, 1 by default; negative counts from the end
j number? the last index, i by default

string.char function#

local char: nosuspend function(...: number): string

Builds a string from the given character codes.

Arguments#

Name Type Description
... number the character codes, each 0 through 255

Returns#

Type Description
string the assembled string

string.dump function#

local dump: nosuspend function(f: any, strip: (boolean | string)?): string

Returns a binary representation of a Lua function that has no upvalues, in a form loadstring accepts.

LuaJIT also accepts a mode string in place of the boolean: s discards debug information as true does, and d writes the entries of a template table in sorted order rather than in the order its keys hash, which is what makes two dumps of one function compare equal across processes.

Arguments#

Name Type Description
f any the function to dump
strip `(boolean string)?`

Returns#

Type Description
string the bytecode string

string.find function#

local find: nosuspend function<Pattern is string, Plain is boolean?>(
    s: string,
    pat: Pattern,
    init: number?,
    plain: Plain?
): unpackof __NuppFindResults(Pattern, Plain)

Finds the first match of pattern pat in s, at or after init. Any captures the pattern has follow the two returned indices.

Type parameters#

Name Description
Pattern
Plain

Arguments#

Name Type Description
s string the string to search
pat Pattern the pattern to look for
init number? where to start, 1 by default; negative counts from the end
plain Plain? whether to match pat literally, ignoring pattern syntax

string.format function#

local format: nosuspend function<Format is string>(
    fmt: Format,
    ...: unpackof __NuppFormatArguments(Format, nupp.Debug)
): string

Formats the arguments into fmt using LuaJIT's bounded-width printf subset, plus %q quoting, %p object identity, and hexadecimal floats with %a/%A.

Type parameters#

Name Description
Format

Arguments#

Name Type Description
fmt Format the format string
... unpackof \_\_NuppFormatArguments(Format, nupp.Debug) the values that the directives consume

Returns#

Type Description
string the formatted string

string.gmatch function#

local gmatch: nosuspend function<Pattern is string>(
    s: string,
    pat: Pattern
): function(): ((unpackof __NuppGmatchResults(Pattern)) | (nil))

Returns an iterator over each successive match of pat in s, or over that match's captures when the pattern has any. Anchors have no special meaning here.

run out

Type parameters#

Name Description
Pattern

Arguments#

Name Type Description
s string the string to scan
pat Pattern the pattern to repeat across s

Returns#

Type Description
`function(): ((unpackof __NuppGmatchResults(Pattern)) (nil))`

string.gsub function#

local gsub: nosuspend function<Pattern is string>(
    s: string,
    pat: Pattern,
    repl: any,
    n: number?
): unpackof __NuppGsubResults(Pattern)

Replaces matches of pat in s. repl may be a string, in which %1 through %9 stand for captures and %0 for the whole match, a table looked up by the first capture, or a function called with the captures.

Type parameters#

Name Description
Pattern

Arguments#

Name Type Description
s string the subject string
pat Pattern the pattern to replace
repl any the replacement string, table or function
n number? how many matches to replace at most, all of them by default

string.len function#

local len: nosuspend function(s: string): integer

Returns the length of s in bytes.

Arguments#

Name Type Description
s string the string to measure

Returns#

Type Description
integer the byte count

string.lower function#

local lower: nosuspend function(s: string): string

Returns s with every ASCII letter folded to lower case.

Arguments#

Name Type Description
s string the string to fold

Returns#

Type Description
string the lowercased string

string.match function#

local match: nosuspend function<Pattern is string>(
    s: string,
    pat: Pattern,
    init: number?
): unpackof __NuppMatchResults(Pattern)

Returns the captures of the first match of pat in s, or the whole match when the pattern has no captures.

Type parameters#

Name Description
Pattern

Arguments#

Name Type Description
s string the string to search
pat Pattern the pattern to look for
init number? where to start, 1 by default; negative counts from the end

string.rep function#

local rep: nosuspend function(s: string, n: number, sep: string?): string

Returns n copies of s, with sep between consecutive copies.

Arguments#

Name Type Description
s string the string to repeat
n number how many copies to produce
sep string? what to place between copies, nothing by default

Returns#

Type Description
string the repeated string

string.reverse function#

local reverse: nosuspend function(s: string): string

Returns the bytes of s in reverse order.

Arguments#

Name Type Description
s string the string to reverse

Returns#

Type Description
string the reversed string

string.sub function#

local sub: nosuspend function(s: string, i: number, j: number?): string

Returns the substring of s running from i through j.

Arguments#

Name Type Description
s string the string to slice
i number the first index; negative counts from the end
j number? the last index, -1 by default

Returns#

Type Description
string the selected substring

string.upper function#

local upper: nosuspend function(s: string): string

Returns s with every ASCII letter folded to upper case.

Arguments#

Name Type Description
s string the string to fold

Returns#

Type Description
string the uppercased string

table#

Table manipulation. These functions work on the array part of a table: the integer keys 1 through #t.

table.clear function#

local clear: function(t: table)

Removes every key from t while keeping the space it has already allocated, so it can be refilled without reallocating.

Arguments#

Name Type Description
t table the table to empty

table.clone function#

local clone: nosuspend function<T is table>(t: T): T

Copies t one level deep: every key it holds directly, and its metatable, are carried over, while a value that is itself a table stays shared between the two. Neither __index nor __pairs is consulted, so what comes back is what next would have walked.

Type parameters#

Name Description
T the table type

Arguments#

Name Type Description
t T the table to copy

Returns#

Type Description
T a new table holding the same keys, values and metatable

table.concat function#

local concat: nosuspend function(t: table, sep: string?, i: number?, j: number?): string

Joins the elements t[i] through t[j], each of which must be a string or a number, into a single string.

Arguments#

Name Type Description
t table the array to join
sep string? what to place between elements, nothing by default
i number? the first index, 1 by default
j number? the last index, #t by default

Returns#

Type Description
string the joined string

table.maxn function#

local maxn: nosuspend function(t: table): number

Returns the largest positive numeric key of t, or 0 when it has none. Deprecated, and unlike #t it also sees keys past a hole.

Arguments#

Name Type Description
t table the table to scan

Returns#

Type Description
number the largest positive numeric key

table.new constructor#

local new: function(narray: number, nhash: number): table

Creates a table preallocated for narray array slots and nhash hash slots, so filling it in does not have to rehash.

Arguments#

Name Type Description
narray number how many array slots to reserve
nhash number how many hash slots to reserve

Returns#

Type Description
table the new table

table.remove function#

local remove: nosuspend function(t: table, pos: number?): any

Removes the element at pos, shifting later elements down.

Arguments#

Name Type Description
t table the array to remove from
pos number? the position to remove, #t by default

Returns#

Type Description
any the element that was removed

table.sort function#

local sort: function<V>(t: {V}, scoped cmp: (function(V, V): boolean)?)

Sorts t in place, between indices 1 and #t. The sort is not stable, and cmp must be a strict order or it may raise.

Type parameters#

Name Description
V the element type

Arguments#

Name Type Description
t {V} the array to sort
scoped cmp (function(V, V): boolean)? returns true when its first argument must come first; < is used when it is omitted

table.insert variable#

local insert: (nosuspend function<V>(t: {V}, value: V): nil)
& (nosuspend function<V>(t: {V}, pos: integer, value: V): nil)

Inserts value at position pos, shifting later elements up. Called with two arguments, appends that value to the end instead.

math#

Mathematical functions and constants, operating on the doubles that plain Lua numbers are.

math.abs function#

local abs: nosuspend function(x: number): number

Returns the absolute value of x.

Arguments#

Name Type Description
x number the number to take the magnitude of

Returns#

Type Description
number the absolute value

math.acos function#

local acos: nosuspend function(x: number): number

Returns the arc cosine of x, in radians.

Arguments#

Name Type Description
x number the cosine to invert, -1 through 1

Returns#

Type Description
number the angle in radians

math.asin function#

local asin: nosuspend function(x: number): number

Returns the arc sine of x, in radians.

Arguments#

Name Type Description
x number the sine to invert, -1 through 1

Returns#

Type Description
number the angle in radians

math.atan function#

local atan: nosuspend function(x: number): number

Returns the arc tangent of x, in radians.

Arguments#

Name Type Description
x number the tangent to invert

Returns#

Type Description
number the angle in radians

math.atan2 function#

local atan2: nosuspend function(y: number, x: number): number

Returns the arc tangent of y / x, using the sign of both arguments to place the result in the right quadrant.

Arguments#

Name Type Description
y number the numerator
x number the denominator

Returns#

Type Description
number the angle in radians

math.ceil function#

local ceil: nosuspend function(x: number): integer

Returns the smallest integer that is not less than x. NaN and the infinities pass through unchanged, so the result is a whole number only when x is finite.

Arguments#

Name Type Description
x number the number to round up

Returns#

Type Description
integer the rounded value

math.cos function#

local cos: nosuspend function(x: number): number

Returns the cosine of x, which is in radians.

Arguments#

Name Type Description
x number the angle in radians

Returns#

Type Description
number the cosine

math.cosh function#

local cosh: nosuspend function(x: number): number

Returns the hyperbolic cosine of x.

Arguments#

Name Type Description
x number the argument

Returns#

Type Description
number the hyperbolic cosine

math.deg function#

local deg: nosuspend function(r: number): number

Converts the angle r from radians to degrees.

Arguments#

Name Type Description
r number the angle in radians

Returns#

Type Description
number the angle in degrees

math.exp function#

local exp: nosuspend function(x: number): number

Returns e raised to the power x.

Arguments#

Name Type Description
x number the exponent

Returns#

Type Description
number the result

math.floor function#

local floor: nosuspend function(x: number): integer

Returns the largest integer that is not greater than x. NaN and the infinities pass through unchanged, so the result is a whole number only when x is finite.

Arguments#

Name Type Description
x number the number to round down

Returns#

Type Description
integer the rounded value

math.fmod function#

local fmod: nosuspend function(x: number, y: number): number

Returns the remainder of x / y, keeping the sign of x.

Arguments#

Name Type Description
x number the dividend
y number the divisor

Returns#

Type Description
number the remainder

math.frexp function#

local frexp: nosuspend function(x: number): (number, number)

Splits x into a fraction in [0.5,1) and an exponent, such that x equals the fraction times 2 raised to the exponent.

Arguments#

Name Type Description
x number the number to split

Returns#

Type Description
number the fraction
number the exponent

math.ldexp function#

local ldexp: nosuspend function(m: number, e: number): number

Returns m times 2 raised to the power e.

Arguments#

Name Type Description
m number the mantissa
e number the exponent

Returns#

Type Description
number the result

math.log function#

local log: nosuspend function(x: number, base: number?): number

Returns the natural logarithm of x, or its logarithm in base.

Arguments#

Name Type Description
x number the number to take the logarithm of
base number? the base to use, e by default

Returns#

Type Description
number the logarithm

math.max function#

local max: function<N is number>(...: N): N

Returns the largest of its arguments. Comparing integers gives an integer back, so a bound taken this way stays usable as an index.

Type parameters#

Name Description
N

Arguments#

Name Type Description
... N the numbers to compare, at least one

Returns#

Type Description
N the largest of them

math.min function#

local min: function<N is number>(...: N): N

Returns the smallest of its arguments. Comparing integers gives an integer back, so a bound taken this way stays usable as an index.

Type parameters#

Name Description
N

Arguments#

Name Type Description
... N the numbers to compare, at least one

Returns#

Type Description
N the smallest of them

math.modf function#

local modf: nosuspend function(x: number): (number, number)

Splits x into its integral and fractional parts, both keeping the sign of x.

Arguments#

Name Type Description
x number the number to split

Returns#

Type Description
number the integral part
number the fractional part

math.pow function#

local pow: nosuspend function(x: number, y: number): number

Returns x raised to the power y, the same as x ^ y.

Arguments#

Name Type Description
x number the base
y number the exponent

Returns#

Type Description
number the result

math.rad function#

local rad: nosuspend function(d: number): number

Converts the angle d from degrees to radians.

Arguments#

Name Type Description
d number the angle in degrees

Returns#

Type Description
number the angle in radians

math.random function#

local random: nosuspend function(): number & function(m: number): number & function(m: number, n: number): number

Returns a pseudo-random number: a float in [0,1) with no arguments, a bounded number with one, or a number between m and n with two.

Arguments#

Name Type Description
m number the upper bound, or the lower bound when n is given too
n number the upper bound

Returns#

Type Description
number the generated number

math.randomseed function#

local randomseed: nosuspend function(seed: number)

Seeds the pseudo-random generator, which starts from a fixed state.

Arguments#

Name Type Description
seed number the seed to start from

math.sin function#

local sin: nosuspend function(x: number): number

Returns the sine of x, which is in radians.

Arguments#

Name Type Description
x number the angle in radians

Returns#

Type Description
number the sine

math.sinh function#

local sinh: nosuspend function(x: number): number

Returns the hyperbolic sine of x.

Arguments#

Name Type Description
x number the argument

Returns#

Type Description
number the hyperbolic sine

math.sqrt function#

local sqrt: nosuspend function(x: number): number

Returns the square root of x.

Arguments#

Name Type Description
x number the number to take the root of

Returns#

Type Description
number the square root

math.tan function#

local tan: nosuspend function(x: number): number

Returns the tangent of x, which is in radians.

Arguments#

Name Type Description
x number the angle in radians

Returns#

Type Description
number the tangent

math.tanh function#

local tanh: nosuspend function(x: number): number

Returns the hyperbolic tangent of x.

Arguments#

Name Type Description
x number the argument

Returns#

Type Description
number the hyperbolic tangent

math.huge variable#

local huge: number

Positive infinity, which compares greater than any other number.

math.pi variable#

local pi: number

The ratio of a circle's circumference to its diameter.

os#

Operating-system facilities: clocks and calendars, the environment, processes and file names.

os.clock function#

local clock: function(): number

Returns the CPU time the program has used, in seconds. It measures intervals of work, not wall-clock time.

Returns#

Type Description
number the CPU seconds consumed so far

os.date function#

local date: function<Format is string>(fmt: Format?, t: number?): __NuppDateResult(Format, DateFields)

Formats the time t as text according to fmt. A leading "!" formats in UTC rather than local time, and a fmt of "*t" returns a table of date fields instead of a string.

A literal fmt decides which of those two the call answers: "t" and "!t" give DateFields, and every other literal gives a string. A fmt the compiler cannot read gives either, so narrow it before use.

Type parameters#

Name Description
Format

Arguments#

Name Type Description
fmt Format? the strftime format, "%c" by default
t number? the time to format, the current time by default

Returns#

Type Description
\_\_NuppDateResult(Format, DateFields) the formatted string, or the field table for "*t"

os.difftime function#

local difftime: function(t2: number, t1: number): number

Returns the number of seconds from t1 to t2.

Arguments#

Name Type Description
t2 number the later time
t1 number the earlier time

Returns#

Type Description
number the difference in seconds

os.execute function#

local execute: function(cmd: string?): any

Runs cmd with the system shell and waits for it. With no argument it instead reports whether a shell is available at all.

Arguments#

Name Type Description
cmd string? the command line to run

Returns#

Type Description
any the command's exit status, or whether a shell exists

os.exit function#

local exit: function(code: any?): never

Ends the process, closing the interpreter state on the way out.

Arguments#

Name Type Description
code any? the exit status: true or 0 for success, false or another number for failure

Returns#

Type Description
never

os.getenv function#

local getenv: function(name: string): string?

Returns the value of the environment variable name.

Arguments#

Name Type Description
name string the variable to read

Returns#

Type Description
string? its value, or nil when it is not set

os.remove function#

local remove: function(path: string): (boolean?, string?)

Deletes the file, or the empty directory, at path.

Arguments#

Name Type Description
path string what to delete

Returns#

Type Description
boolean? true on success, or nil on failure
string? the reason it failed

os.rename function#

local rename: function(from: string, to: string): (boolean?, string?)

Renames the file or directory at from to to.

Arguments#

Name Type Description
from string the existing path
to string the new path

Returns#

Type Description
boolean? true on success, or nil on failure
string? the reason it failed

os.time function#

local time: function(spec: table?): number

Returns the current time, or the time that spec describes.

Arguments#

Name Type Description
spec table? a table with year, month and day, and optionally hour, min, sec and isdst

Returns#

Type Description
number the time, in the system's own epoch-based encoding

os.tmpname function#

local tmpname: function(): string

Returns a file name usable for a temporary file. The file itself is neither created nor removed for you.

Returns#

Type Description
string the temporary file name

package#

package.loadlib function#

local loadlib: function(path: string, symbol: string): (any, string?)

Opens a shared object and answers the named C entry point, or nil and why when it could not be opened.

Arguments#

Name Type Description
path string
symbol string

Returns#

Type Description
any
string?

package.config variable#

local config: string

Platform path separators and template markers.

package.cpath variable#

local cpath: string

Search templates used by require for C modules.

package.loaded variable#

local loaded: {[string]: any}

Every module require has already returned, by the name it was asked for. Writing an entry makes that name resolve without a search.

package.loaders variable#

local loaders: {function(string): any}

Lua 5.1 and Lua 5.2 names for the module-loader chain.

package.path variable#

local path: string

Search templates used by require for Lua modules.

package.preload variable#

local preload: {[string]: function(...: any): any}

Modules made available without consulting the filesystem.

package.searchers variable#

local searchers: {function(string): any}?

io#

io.close function#

local close: function(f: LuaFile?): boolean?

Closes f, or the default output file when it is omitted.

Arguments#

Name Type Description
f LuaFile? the file to close

Returns#

Type Description
boolean? whether the file closed cleanly

io.input function#

local input: function(f: (LuaFile | string)?): LuaFile

Sets the default input file, opening f first when it is a name. With no argument it returns the current one instead.

Arguments#

Name Type Description
f `(LuaFile string)?`

Returns#

Type Description
LuaFile the default input file

io.lines function#

local lines: function(path: string?): nosuspend function(): string?

Returns an iterator over the lines of the file at path, closing it once the iterator runs out, or over the default input file when path is omitted.

Arguments#

Name Type Description
path string? the file to read, or nil for the default input file

Returns#

Type Description
nosuspend function(): string? an iterator yielding one line at a time, and nil once the file is read

io.open function#

local open: function(path: string, mode: string?): (affine(LuaFile, _)?, string?)

Opens the file at path. Modes are "r", "w" and "a", with "+" added for update and a trailing "b" for binary.

Arguments#

Name Type Description
path string the file to open
mode string? the mode to open it in, "r" by default

Returns#

Type Description
affine(LuaFile, \_)? the file handle, or nil when it cannot be opened
string? the reason it could not be opened

io.output function#

local output: function(f: (LuaFile | string)?): LuaFile

Sets the default output file, opening f first when it is a name. With no argument it returns the current one instead.

Arguments#

Name Type Description
f `(LuaFile string)?`

Returns#

Type Description
LuaFile the default output file

io.popen function#

local popen: function(cmd: string, mode: string?): (affine(LuaFile, _)?, string?)

Runs cmd in a separate process and returns a handle on one of its streams: its standard output for "r", its standard input for "w".

Arguments#

Name Type Description
cmd string the command line to run
mode string? which stream to connect, "r" by default

Returns#

Type Description
affine(LuaFile, \_)? the file handle, or nil when the process cannot start
string? the reason it could not start

io.read function#

local read: function(...: any): any

Reads the default input file according to the given formats: "l" for a line, "n" for a number, "*a" for the rest, or a byte count.

Arguments#

Name Type Description
... any the formats to read, "*l" by default

Returns#

Type Description
any one value per format, or nil where the read came up short

io.tmpfile function#

local tmpfile: function(): affine(LuaFile, _)?

Opens a temporary file in update mode, removed when the program ends.

Returns#

Type Description
affine(LuaFile, \_)? the file handle

io.write function#

local write: function(...: any): any

Writes each argument, which must be a string or a number, to the default output file.

Arguments#

Name Type Description
... any the values to write

Returns#

Type Description
any the file that was written to

io.stderr variable#

local stderr: LuaFile

The standard error stream.

io.stdin variable#

local stdin: LuaFile

The standard input stream.

io.stdout variable#

local stdout: LuaFile

The standard output stream.

io.type variable#

local type: nosuspend function(value: any): ("file" | "closed file")?

Classifies an open or closed file handle.

coroutine#

coroutine.create function#

local create: function(f: any): thread

Creates a coroutine with f as its body. The body does not start running until the first resume.

Arguments#

Name Type Description
f any the function to run inside the coroutine

Returns#

Type Description
thread the new coroutine

coroutine.isyieldable function#

local isyieldable: function(): boolean

Whether the running coroutine is allowed to yield, which is false on the main coroutine.

Returns#

Type Description
boolean whether a yield would succeed here

coroutine.resume function#

local resume: function<A...>(co: thread, A...): ...any

Starts or continues co. The extra arguments go to its body on the first call, and become the results of the yield that suspended it on later ones.

Type parameters#

Name Description
A

Arguments#

Name Type Description
co thread the coroutine to run
? A...

coroutine.running function#

local running: function(): (thread?, boolean)

Returns the coroutine that is running.

Returns#

Type Description
thread? the running coroutine
boolean whether that is the main coroutine

coroutine.status function#

local status: function(co: thread): string

Returns the state of co: "running", "suspended", "normal" for one that resumed another coroutine, or "dead".

Arguments#

Name Type Description
co thread the coroutine to inspect

Returns#

Type Description
string the state name

coroutine.wrap function#

local wrap: function(f: any): any

Creates a coroutine and returns a function that resumes it, passing along its own arguments. Errors propagate to the caller instead of being returned as a status.

Arguments#

Name Type Description
f any the function to run inside the coroutine

Returns#

Type Description
any a function that resumes the coroutine

coroutine.yield function#

local yield: function<Y...>(Y...): ...any

Suspends the running coroutine. The arguments become the results of the resume that started it.

Type parameters#

Name Description
Y

Arguments#

Name Type Description
? Y...

bit#

bit.arshift function#

local arshift: nosuspend function(x: number, n: number): integer

Shifts x right by n bits, copying the sign bit down.

Arguments#

Name Type Description
x number the number to shift
n number how many bits to shift by, taken modulo 32

Returns#

Type Description
integer the shifted value

bit.band function#

local band: nosuspend function(...: number): integer

Returns the bitwise and of every argument.

Arguments#

Name Type Description
... number the numbers to combine

Returns#

Type Description
integer the combined value

bit.bnot function#

local bnot: nosuspend function(x: number): integer

Returns the bitwise complement of x.

Arguments#

Name Type Description
x number the number to complement

Returns#

Type Description
integer the complement

bit.bor function#

local bor: nosuspend function(...: number): integer

Returns the bitwise or of every argument.

Arguments#

Name Type Description
... number the numbers to combine

Returns#

Type Description
integer the combined value

bit.bswap function#

local bswap: nosuspend function(x: number): integer

Swaps the byte order of x, converting between endiannesses.

Arguments#

Name Type Description
x number the number to byte-swap

Returns#

Type Description
integer the swapped value

bit.bxor function#

local bxor: nosuspend function(...: number): integer

Returns the bitwise exclusive or of every argument.

Arguments#

Name Type Description
... number the numbers to combine

Returns#

Type Description
integer the combined value

bit.lshift function#

local lshift: nosuspend function(x: number, n: number): integer

Shifts x left by n bits, filling with zeros.

Arguments#

Name Type Description
x number the number to shift
n number how many bits to shift by, taken modulo 32

Returns#

Type Description
integer the shifted value

bit.rol function#

local rol: nosuspend function(x: number, n: number): integer

Rotates x left by n bits.

Arguments#

Name Type Description
x number the number to rotate
n number how many bits to rotate by, taken modulo 32

Returns#

Type Description
integer the rotated value

bit.ror function#

local ror: nosuspend function(x: number, n: number): integer

Rotates x right by n bits.

Arguments#

Name Type Description
x number the number to rotate
n number how many bits to rotate by, taken modulo 32

Returns#

Type Description
integer the rotated value

bit.rshift function#

local rshift: nosuspend function(x: number, n: number): integer

Shifts x right by n bits without sign extension.

Arguments#

Name Type Description
x number the number to shift
n number how many bits to shift by, taken modulo 32

Returns#

Type Description
integer the shifted value

bit.tobit function#

local tobit: nosuspend function(x: number): integer

Normalizes x into the signed 32-bit integer range, wrapping around.

Arguments#

Name Type Description
x number the number to normalize

Returns#

Type Description
integer the normalized value

bit.tohex function#

local tohex: nosuspend function(x: number, n: number?): string

Returns x in hexadecimal, using n digits.

Arguments#

Name Type Description
x number the number to convert
n number? how many digits to print, 8 by default; a negative count prints uppercase digits

Returns#

Type Description
string the hexadecimal text

jit#

jit.attach function#

local attach: function(callback: function(...: any), event: string?)

Adds or removes a handler for a compiler event, so a program can watch the JIT as it works. Omitting event removes the handler.

The handler's own signature is decided by the event, which is why this one is variadic:

  • "bc": (func), once per function the VM records bytecode for. * "trace": (what, tr, func, pc, otr, oex), where what is "start", "stop", "abort", "flush" or "free". On "abort", otr is an error code to look up in require("jit.vmdef").traceerr and oex is its argument; on "start" for a side trace they are the parent trace and its exit.
  • "record": (tr, func, pc, depth), per bytecode recorded. * "texit": (tr, ex, ngpr, nfpr), per trace exit.

A handler runs inside the compiler, so it must not allocate heavily, raise, or re-enter the VM in ways that would trigger further compilation. Dropping the last reference to a handler does not detach it: hold onto it and pass it back with no event to remove it.

Arguments#

Name Type Description
callback function(...: any) the handler to add, or the one to remove
event string? which event to attach to, or nil to detach

jit.flush function#

local flush: function(f: any?, recursive: boolean?)

Flushes compiled code, for f or for the whole cache when it is omitted, so the affected code is traced again from scratch. A trace number flushes that one trace.

Arguments#

Name Type Description
f any? the function to flush, a trace number, or nil for the whole cache
recursive boolean? whether to flush nested functions too

jit.off function#

local off: function(f: any?, recursive: boolean?)

Turns compilation off for f, or for the whole VM when it is omitted, leaving already compiled code in place.

Arguments#

Name Type Description
f any? the function to disable, or nil for the whole VM
recursive boolean? whether to apply the change to nested functions too

jit.on function#

local on: function(f: any?, recursive: boolean?)

Turns compilation on for f, or for the whole VM when it is omitted.

Arguments#

Name Type Description
f any? the function to enable, or nil for the whole VM
recursive boolean? whether to apply the change to nested functions too

jit.security function#

local security: function(param: string): any

Reports how the VM was built for a security-relevant parameter, such as "prng" or "strhash".

Arguments#

Name Type Description
param string the parameter to report on

Returns#

Type Description
any the setting in force

jit.status function#

local status: function(): (boolean, any)

Reports whether the compiler is enabled.

Returns#

Type Description
boolean whether compilation is currently on
any the optimization flags in force, one per result

jit.arch variable#

local arch: string

The target architecture, such as "x64" or "arm64".

jit.opt variable#

local opt: {start: function(...: any)}

The optimization submodule. jit.opt.start takes flags such as "hotloop=10" or "-fold", each as its own argument.

jit.os variable#

local os: string

The operating system, such as "Linux", "OSX" or "Windows".

jit.version variable#

local version: string

The LuaJIT version string, such as "LuaJIT 2.1.0".

jit.version_num variable#

local version_num: number

The LuaJIT version as a number, where 2.1.0 reads as 20100.

debug#

debug.gethook function#

local gethook: function(): any

Returns the hook currently installed.

Returns#

Type Description
any the hook function, its mask and its count

debug.getinfo function#

local getinfo: function(f: any, what: string?): any

Describes a function, or the activation record at a stack level.

Arguments#

Name Type Description
f any the function to describe, or a stack level counted from here
what string? which fields to fill in, all of them by default

Returns#

Type Description
any the description table, or nil when the level is out of range

debug.getlocal function#

local getlocal: function(level: any, idx: number): (string?, any)

Reads local variable idx of the function at a stack level.

Arguments#

Name Type Description
level any the stack level, or a function to inspect
idx number the 1-based index of the local

Returns#

Type Description
string? the variable's name, or nil past the last one
any its current value

debug.getmetatable function#

local getmetatable: function(v: any): table?

Returns the metatable of v, ignoring any __metatable field.

Arguments#

Name Type Description
v any the value to inspect

Returns#

Type Description
table? the metatable, or nil when there is none

debug.getregistry function#

local getregistry: function(): table

Returns the registry, the table where C code anchors its references.

Returns#

Type Description
table the registry table

debug.getupvalue function#

local getupvalue: function(f: any, idx: number): (string?, any)

Reads upvalue idx of the function f.

Arguments#

Name Type Description
f any the function to inspect
idx number the 1-based index of the upvalue

Returns#

Type Description
string? the upvalue's name, or nil past the last one
any its current value

debug.sethook function#

local sethook: function(...: any)

Installs a debug hook: a function, a mask built from "c", "r" and "l", and an optional instruction count.

Arguments#

Name Type Description
... any the hook function, its mask, and the count

debug.setlocal function#

local setlocal: function(level: any, idx: number, v: any): string?

Assigns v to local variable idx at a stack level.

Arguments#

Name Type Description
level any the stack level to write into
idx number the 1-based index of the local
v any the value to store

Returns#

Type Description
string? the variable's name, or nil past the last one

debug.setmetatable function#

local setmetatable: function(v: any, mt: table?): any

Sets v's metatable, ignoring any __metatable field.

Arguments#

Name Type Description
v any the value to change
mt table? the new metatable, or nil to remove the current one

Returns#

Type Description
any v

debug.setupvalue function#

local setupvalue: function(f: any, idx: number, v: any): string?

Assigns v to upvalue idx of the function f.

Arguments#

Name Type Description
f any the function to modify
idx number the 1-based index of the upvalue
v any the value to store

Returns#

Type Description
string? the upvalue's name, or nil past the last one

debug.traceback function#

local traceback: function(msg: any?, level: number?): string

Returns a traceback of the call stack, with msg at the front.

Arguments#

Name Type Description
msg any? the message to prepend, returned as-is when not a string
level number? the stack level to start at, 1 by default

Returns#

Type Description
string the traceback text

debug.upvaluejoin function#

local upvaluejoin: function(f: any, idx: number, source: any, sourceIdx: number)

Makes one function's upvalue refer to the same lexical cell as another's.

Arguments#

Name Type Description
f any the function whose upvalue is replaced
idx number its 1-based upvalue index
source any the function providing the cell
sourceIdx number its 1-based upvalue index

ffi#

Declarations for LuaJIT's ffi module, loaded for require("ffi").

Most C work in Nupp goes through cdef declarations and struct, which need none of this. These are for the cases that stay explicitly at the machine level: converting C strings back to Lua strings, bulk memory moves, casts, and loading libraries by hand.

The names are the library's own, so they are never restyled.

ffi.ffi record#

local record ffi
    string: function(ptr: any, len: (integer | int64 | uint64)?): string
    new: function(ct: any, ...: any): any
    typeof: function(ct: any, ...: any): any
    cast: function(ct: any, value: any): any
    metatype: function(ct: any, mt: table): any
    gc: function(obj: any, finalizer: any): any
    istype: function(ct: any, obj: any): boolean
    sizeof: function(ct: any, nelem: integer?): integer?
    alignof: function(ct: any): integer
    offsetof: function(ct: any, field: string): integer?
    copy: function(borrows dst: any, borrows src: any, len: (integer | int64 | uint64)?)
    fill: function(dst: any, len: integer | int64 | uint64, c: integer?)
    cdef: function(def: string)
    load: function(name: string, global: boolean?): any
    abi: function(param: string): boolean
    errno: function(newerr: integer?): integer
    typeinfo: function(id: integer): any
    C: any

    os: string
    arch: string
end

Methods#

string#
string: function(ptr: any, len: (integer | int64 | uint64)?): string

Copies a C string (or len bytes) into a Lua string. A size_t read out of C memory is a boxed length, and the call takes it as readily as a number.

Arguments#
Name Type Description
ptr any
len `(integer int64
Returns#
Type Description
string

new#
new: function(ct: any, ...: any): any

Allocates a cdata object of the given type.

Arguments#
Name Type Description
ct any
... any
Returns#
Type Description
any

typeof#
typeof: function(ct: any, ...: any): any

Returns the ctype object for a C type declaration.

Arguments#
Name Type Description
ct any
... any
Returns#
Type Description
any

cast#
cast: function(ct: any, value: any): any

Reinterprets a value as another C type.

Arguments#
Name Type Description
ct any
value any
Returns#
Type Description
any

metatype#
metatype: function(ct: any, mt: table): any

Associates a metatable with a ctype; returns the ctype.

Arguments#
Name Type Description
ct any
mt table
Returns#
Type Description
any

gc#
gc: function(obj: any, finalizer: any): any

Attaches a finalizer to a cdata object; returns the object.

Arguments#
Name Type Description
obj any
finalizer any
Returns#
Type Description
any

istype#
istype: function(ct: any, obj: any): boolean

True when obj has the given ctype.

Arguments#
Name Type Description
ct any
obj any
Returns#
Type Description
boolean

sizeof#
sizeof: function(ct: any, nelem: integer?): integer?

Size in bytes, or nil for incomplete types.

Arguments#
Name Type Description
ct any
nelem integer?
Returns#
Type Description
integer?

alignof#
alignof: function(ct: any): integer

Alignment in bytes.

Arguments#
Name Type Description
ct any
Returns#
Type Description
integer

offsetof#
offsetof: function(ct: any, field: string): integer?

Byte offset of a struct field.

Arguments#
Name Type Description
ct any
field string
Returns#
Type Description
integer?

copy#
copy: function(borrows dst: any, borrows src: any, len: (integer | int64 | uint64)?)

Bulk copy between cdata (or from a Lua string).

Arguments#
Name Type Description
borrows dst any
borrows src any
len `(integer int64

fill#
fill: function(dst: any, len: integer | int64 | uint64, c: integer?)

Fills memory with a byte value (zero by default).

Arguments#
Name Type Description
dst any
len `integer int64
c integer?

cdef#
cdef: function(def: string)

Adds C declarations to the global C namespace.

Arguments#
Name Type Description
def string

load#
load: function(name: string, global: boolean?): any

Loads a shared library and returns its namespace.

Arguments#
Name Type Description
name string
global boolean?
Returns#
Type Description
any

abi#
abi: function(param: string): boolean

True when the ABI parameter holds (e.g. "64bit", "le").

Arguments#
Name Type Description
param string
Returns#
Type Description
boolean

errno#
errno: function(newerr: integer?): integer

Reads, and optionally sets, the C errno.

Arguments#
Name Type Description
newerr integer?
Returns#
Type Description
integer

typeinfo#
typeinfo: function(id: integer): any

Reads LuaJIT's own record of a declared C type. Internal to the implementation rather than part of the documented FFI, but it is how a program can learn what a cdef declared.

Arguments#
Name Type Description
id integer
Returns#
Type Description
any

Fields#

C#
C: any

The default C namespace: symbols in the running process.

os#
os: string

arch#
arch: string

string.buffer#

Declarations for LuaJIT's string.buffer module, loaded for require("string.buffer").

A buffer is a FIFO: the put* and encode methods append to the end, and the get* and decode methods consume from the front. Methods chain; putcdata, ref, and reserve sit at the FFI boundary.

Length with #buf, concatenation with .., and tostring are metamethods, so they are not members of the record below; use buf:tostring().

string.buffer.decode function#

local decode: function(s: string): any

Deserializes a whole encoded string. Raises on malformed input, and also when anything is left over after one top-level object.

Arguments#

Name Type Description
s string the encoded bytes

Returns#

Type Description
any the decoded value, of any supported type

string.buffer.encode function#

local encode: function(v: any): string

Serializes v to a string. Raises on unsupported types, circular references, and nesting too deep to encode.

Arguments#

Name Type Description
v any the value to serialize

Returns#

Type Description
string the encoded bytes

string.buffer.new constructor#

local new: function(size: (integer | table)?, options: table?): Buffer

Creates a buffer. The options table may carry a dict array of string keys that occur often and a metatable array of metatables, which the serializer encodes as indexes; an encoder and its decoder must share them, and neither table may be modified afterwards.

Arguments#

Name Type Description
size `(integer table)?`
options table? the serialization options

Returns#

Type Description
Buffer the new buffer

string.buffer.Buffer record#

record Buffer
    metamethod __len: function(self): integer
    metamethod __concat: function(self, other: any): string
    metamethod __tostring: function(self): string
    put: function(exclusive b: Buffer, ...: any): Buffer borrows (b)
    putf: function(exclusive b: Buffer, fmt: string, ...: any): Buffer borrows (b)
    putcdata: function(exclusive b: Buffer, data: voidptr, len: integer): Buffer borrows (b)
    set: function(exclusive b: Buffer, data: any, len: integer?): Buffer borrows (b)
    get: function(exclusive b: Buffer, ...: integer?): (string,...string)
    tostring: function(b: Buffer): string
    reset: function(exclusive b: Buffer): Buffer borrows (b)
    free: function(exclusive b: Buffer): Buffer borrows (b)
    skip: function(exclusive b: Buffer, n: integer): Buffer borrows (b)
    ref: function(borrows b: Buffer): (uint8[?] borrows (b), integer)
    reserve: function(exclusive b: Buffer, size: integer): (uint8[?] borrows (b), integer)
    commit: function(exclusive b: Buffer, used: integer): Buffer borrows (b)
    encode: function(exclusive b: Buffer, obj: any): Buffer borrows (b)
    decode: function(exclusive b: Buffer): any
end

A mutable, binary-transparent byte sequence. Methods with nothing else to return hand back the buffer itself, so calls chain.

Exported, so code that passes buffers around can name the type: function render(out: string.buffer.Buffer): string.buffer.Buffer.

Methods#

__len#
__len: function(self): integer
Arguments#
Name Type Description
? self
Returns#
Type Description
integer

__concat#
__concat: function(self, other: any): string
Arguments#
Name Type Description
? self
other any
Returns#
Type Description
string

__tostring#
__tostring: function(self): string
Arguments#
Name Type Description
? self
Returns#
Type Description
string

put#
put: function(exclusive b: Buffer, ...: any): Buffer borrows (b)

Appends each argument: a string, a number, another buffer, or any object with a __tostring metamethod.

Arguments#
Name Type Description
exclusive b Buffer the buffer to append to
... any the values to append, in order
Returns#
Type Description
Buffer borrows (b) b

putf#
putf: function(exclusive b: Buffer, fmt: string, ...: any): Buffer borrows (b)

Appends the arguments formatted by fmt, which takes the same directives as string.format.

Arguments#
Name Type Description
exclusive b Buffer the buffer to append to
fmt string the format string
... any the values that the directives consume
Returns#
Type Description
Buffer borrows (b) b

putcdata#
putcdata: function(exclusive b: Buffer, data: voidptr, len: integer): Buffer borrows (b)

Appends len bytes read from the memory that data points to. The cdata object has to be convertible to a pointer.

Arguments#
Name Type Description
exclusive b Buffer the buffer to append to
data voidptr the memory to copy from
len integer how many bytes to copy
Returns#
Type Description
Buffer borrows (b) b

set#
set: function(exclusive b: Buffer, data: any, len: integer?): Buffer borrows (b)

Replaces the buffer contents with a reference to data, freeing any space already allocated. Nothing is copied until the buffer is written to again, and the reference keeps data alive meanwhile.

Arguments#
Name Type Description
exclusive b Buffer the buffer to reset onto data
data any the string, or cdata pointer, to reference
len integer? how many bytes data holds, required for cdata
Returns#
Type Description
Buffer borrows (b) b

get#
get: function(exclusive b: Buffer, ...: integer?): (string,...string)

Consumes bytes from the front of the buffer and returns them. With no argument the whole buffer is consumed; each further argument takes one more string, and a nil argument takes whatever remains.

Arguments#
Name Type Description
exclusive b Buffer the buffer to read from
... integer? how many bytes each returned string takes
Returns#
Type Description
string one string per argument, or the whole buffer when given none

tostring#
tostring: function(b: Buffer): string

Returns the buffer contents as a string, without consuming them.

Arguments#
Name Type Description
b Buffer the buffer to read
Returns#
Type Description
string the buffer contents

reset#
reset: function(exclusive b: Buffer): Buffer borrows (b)

Empties the buffer, keeping the space it has already allocated so it can be refilled without reallocating.

Arguments#
Name Type Description
exclusive b Buffer the buffer to empty
Returns#
Type Description
Buffer borrows (b) b

free#
free: function(exclusive b: Buffer): Buffer borrows (b)

Frees the buffer space at once, leaving the object itself intact and empty. The collector does this on its own, so it is only worth calling when the memory has to go back immediately.

Arguments#
Name Type Description
exclusive b Buffer the buffer to free
Returns#
Type Description
Buffer borrows (b) b

skip#
skip: function(exclusive b: Buffer, n: integer): Buffer borrows (b)

Consumes n bytes from the front of the buffer and discards them, stopping at the end of the data.

Arguments#
Name Type Description
exclusive b Buffer the buffer to skip in
n integer how many bytes to discard
Returns#
Type Description
Buffer borrows (b) b

ref#
ref: function(borrows b: Buffer): (uint8[?] borrows (b), integer)

Returns a pointer to the buffer data, for zero-copy reads and in-place writes. The data is not zero-terminated, so the length has to travel with the pointer.

Arguments#
Name Type Description
borrows b Buffer the buffer to point into
Returns#
Type Description
uint8\[?\] borrows (b) the unconsumed data, as the zero-based uint8_t * view that bytewise reads and writes go through
integer how many bytes are readable there

reserve#
reserve: function(exclusive b: Buffer, size: integer): (uint8[?] borrows (b), integer)

Reserves at least size bytes of write space and returns a pointer to it. The space is uninitialized, and joins the buffer data only once commit says how much of it was written.

Arguments#
Name Type Description
exclusive b Buffer the buffer to reserve space in
size integer how many bytes are needed at least
Returns#
Type Description
uint8\[?\] borrows (b) the write space, as the zero-based uint8_t * view that bytewise writes go through
integer how many bytes are actually available, at least size

commit#
commit: function(exclusive b: Buffer, used: integer): Buffer borrows (b)

Appends the first used bytes of the space handed out by the last reserve to the buffer data.

Arguments#
Name Type Description
exclusive b Buffer the buffer that space was reserved in
used integer how many bytes were written
Returns#
Type Description
Buffer borrows (b) b

encode#
encode: function(exclusive b: Buffer, obj: any): Buffer borrows (b)

Serializes obj and appends the encoding to the buffer. Encodings concatenate, so several objects can be streamed into one buffer.

Arguments#
Name Type Description
exclusive b Buffer the buffer to append to
obj any the value to serialize
Returns#
Type Description
Buffer borrows (b) b

decode#
decode: function(exclusive b: Buffer): any

Deserializes one object from the front of the buffer, leaving any data after it in place. Raises on malformed or truncated input.

Arguments#
Name Type Description
exclusive b Buffer the buffer to read from
Returns#
Type Description
any the decoded value, of any supported type

jit.util#

Declarations for LuaJIT's jit.util module, loaded for require("jit.util").

Not a field on jit: LuaJIT registers this under package.loaded only, so it has to be require()d.

Everything here reads VM internals, meaning bytecode, IR, snapshots and machine code, whose shape tracks the LuaJIT build rather than any stable contract, and an index that does not exist answers nil rather than raising. Treat the results as diagnostic output to print, not as data to compute with.

jit.util.JitUtil record#

local record JitUtil
    funcinfo: function(func: any, pc: integer?): {[string]: any}
    funcbc: function(func: any, pc: integer): (integer?, integer?)
    funck: function(func: any, idx: integer): any
    funcuvname: function(func: any, idx: integer): string?
    traceinfo: function(tr: integer): {[string]: any}?
    traceir: function(tr: integer, idx: integer): (integer, integer, integer, integer, integer)
    tracek: function(tr: integer, idx: integer): (any, integer, integer?)
    tracesnap: function(tr: integer, sn: integer): {[string]: any}?
    tracemc: function(tr: integer): (string?, integer?, integer?)
    traceexitstub: function(tr: integer, exitno: integer): integer?
    ircalladdr: function(idx: integer): integer
end

Methods#

funcinfo#
funcinfo: function(func: any, pc: integer?): {[string]: any}

Describes a function, or the bytecode position pc inside it.

The two kinds of function answer with different keys, so read the one you want only after checking it is there. A Lua function reports source, loc, linedefined, lastlinedefined, params, stackslots, upvalues, bytecodes, gcconsts, nconsts, children, isvararg, proto, and currentline when pc is given. A builtin reports ffid, addr and upvalues, and nothing else.

Arguments#
Name Type Description
func any the function to describe
pc integer? the bytecode index to resolve currentline from
Returns#
Type Description
{\[string\]: any} a freshly allocated description table

funcbc#
funcbc: function(func: any, pc: integer): (integer?, integer?)

Reads one bytecode instruction.

Arguments#
Name Type Description
func any the function to read from
pc integer the bytecode index, counting from 0
Returns#
Type Description
integer? the instruction word, or nil when pc is past the end
integer? the opcode, an index into the packed bcnames of require("jit.vmdef")

funck#
funck: function(func: any, idx: integer): any

Reads a constant from a function's constant table.

Arguments#
Name Type Description
func any the function to read from
idx integer the constant index: non-negative for a number, negative for a garbage-collected constant
Returns#
Type Description
any the constant, or nil when the index is out of range

funcuvname#
funcuvname: function(func: any, idx: integer): string?

Names an upvalue.

Arguments#
Name Type Description
func any the function to read from
idx integer the upvalue index, counting from 0
Returns#
Type Description
string? the name, or nil when the index is out of range

traceinfo#
traceinfo: function(tr: integer): {[string]: any}?

Describes a compiled trace: its link, extent, exit count, and the machine code it occupies.

Arguments#
Name Type Description
tr integer the trace number
Returns#
Type Description
{\[string\]: any}? the description table, or nil when no such trace exists

traceir#
traceir: function(tr: integer, idx: integer): (integer, integer, integer, integer, integer)

Reads one IR instruction from a trace.

Arguments#
Name Type Description
tr integer the trace number
idx integer the IR reference
Returns#
Type Description
integer the IR mode, the opcode and type byte, the two operands, and the previous reference in the chain
integer
integer
integer
integer

tracek#
tracek: function(tr: integer, idx: integer): (any, integer, integer?)

Reads a constant referenced by a trace's IR.

Arguments#
Name Type Description
tr integer the trace number
idx integer the IR reference of the constant
Returns#
Type Description
any the constant value
integer its IR type
integer? the stack slot it was loaded from, when there was one

tracesnap#
tracesnap: function(tr: integer, sn: integer): {[string]: any}?

Reads a trace snapshot: the stack map an exit restores from.

Arguments#
Name Type Description
tr integer the trace number
sn integer the snapshot index
Returns#
Type Description
{\[string\]: any}? the snapshot table, or nil when the index is out of range

tracemc#
tracemc: function(tr: integer): (string?, integer?, integer?)

Returns a trace's machine code.

Arguments#
Name Type Description
tr integer the trace number
Returns#
Type Description
string? the machine code as a byte string
integer? the address it was assembled to run at
integer? the loop offset within it

traceexitstub#
traceexitstub: function(tr: integer, exitno: integer): integer?

Address of the exit stub for one of a trace's exits.

Arguments#
Name Type Description
tr integer the trace number
exitno integer the exit number
Returns#
Type Description
integer? the address, or nil when the exit does not exist

ircalladdr#
ircalladdr: function(idx: integer): integer

Address of an IR call target, for naming a call in a disassembly.

Arguments#
Name Type Description
idx integer the index into the IR call table, which require("jit.vmdef").ircall names
Returns#
Type Description
integer the address

jit.profile#

Declarations for LuaJIT's jit.profile module, loaded for require("jit.profile").

The low-level sampling profiler: a timer interrupt, a callback, and a stack dumper. It samples and attributes; deciding what a report looks like is the caller's job, which is why there is no report type here.

One profiler runs at a time, and start while one is running replaces it.

jit.profile.JitProfile record#

local record JitProfile
    start: function(mode: string, cb: function(thread: any, samples: integer, vmstate: string))
    stop: function()
    dumpstack: function(thread: any?, fmt: string, depth: integer): string
end

Methods#

start#
start: function(mode: string, cb: function(thread: any, samples: integer, vmstate: string))

Starts sampling, calling cb for each batch of samples.

mode is a string of option characters:

  • "f": sample the function, "l" the line, "z" the zone (see the bundled jit.zone module).
  • "i<n>": sample every n milliseconds, 10 by default. Below about 10 the timer starts taking real time away from the thread it is measuring.
  • "r": report raw sample counts rather than accumulating. * "v": report the VM state.

The callback runs on the interrupted thread, so it must not allocate heavily or raise; it is also the only place dumpstack sees the sampled stack. vmstate is one character: "N" running compiled code, "I" interpreting, "C" in a C function, "G" collecting, "J" compiling.

Arguments#
Name Type Description
mode string the option string described above
cb function(thread: any, samples: integer, vmstate: string) receives the sampled thread, how many samples this batch stands for, and the VM state

stop#
stop: function()

Stops the running profiler. Safe to call when none is running.

dumpstack#
dumpstack: function(thread: any?, fmt: string, depth: integer): string

Renders a sampled stack as text.

fmt is a template applied once per frame: "p" is the function, "f" its name, "F" the name with its source, and "l" the source line. Anything else is a literal, so the tail of the format is the separator between frames.

"Z" is not a frame at all: it stops the format there on the last frame, which is how the separator is kept from trailing. "lZ;" is a;b;c, where "l;" would be a;b;c;.

depth counts frames from the top; a negative count walks from the bottom instead, which is the order a collapsed-stack profile wants. Frames the JIT inlined into a trace are not there to walk, so a compiled call chain arrives shorter than its source reads.

Meaningful only for the thread handed to a start callback, and only while that callback is running.

Arguments#
Name Type Description
thread any? the sampled thread; omit for the current one
fmt string the per-frame format described above
depth integer how many frames, negative to walk bottom-up
Returns#
Type Description
string the rendered stack

jit.zone#

Declarations for LuaJIT's jit.zone module, loaded for require("jit.zone").

A hierarchical zone stack, which is what jit.profile's "z" mode and dumpstack's "Z" frame format attribute samples to. Pushing names a region of work; popping ends it.

The value is literally the stack: a plain table whose array part holds the pushed names, with flush and get on it and __call doing the pushing and popping. Reading the array directly is possible but not typed here, so it needs a cast.

The stock implementation does its table work whether or not a profiler is listening, which makes an instrumented hot path pay for zones it is not being measured with. nupp.profile.zone wraps this and gates it; prefer that over calling this module directly.

jit.zone.Zone record#

record Zone
    metamethod __call: function(z: Zone, name: string?): string?
    flush: function(z: Zone)
    get: function(z: Zone): string?
end

The profiler zone stack. Callable: with a name it pushes, with no argument it pops and returns the name it removed.

Exported, so code that holds the stack can name what it is holding.

Methods#

__call#
__call: function(z: Zone, name: string?): string?

Pushes name, or pops and returns the innermost zone when name is omitted. Popping an empty stack raises "empty zone stack".

Arguments#
Name Type Description
z Zone the zone stack
name string? the zone to push, or nil to pop
Returns#
Type Description
string? the popped zone, when popping

flush#
flush: function(z: Zone)

Discards every pushed zone, leaving the stack empty.

Arguments#
Name Type Description
z Zone the zone stack

get#
get: function(z: Zone): string?

Returns the innermost zone without popping it.

Arguments#
Name Type Description
z Zone the zone stack
Returns#
Type Description
string? the innermost zone, or nil when nothing is pushed

Types#

The types the declarations above name in their signatures. They are written by the prelude rather than by a program, which is why they have no module of their own to be documented from.

DateFields interface#

local interface DateFields
    year: integer
    month: integer
    day: integer
    hour: integer
    min: integer
    sec: integer
    wday: integer
    yday: integer
    isdst: boolean
end

The fields os.date("*t") answers.

Every one is present, which is what separates this from the table os.time accepts: there a partial civil time is completed for you, and here the platform has already done it. wday counts from Sunday and yday from January 1st, both from 1.

Fields#

year#
year: integer

The full year, not an offset from 1900.

month#
month: integer

The month, 1 through 12.

day#
day: integer

The day of the month, 1 through 31.

hour#
hour: integer

The hour, 0 through 23.

min#
min: integer

The minute, 0 through 59.

sec#
sec: integer

The second, 0 through 60, the last of which is a leap second.

wday#
wday: integer

The day of the week, 1 for Sunday.

yday#
yday: integer

The day of the year, 1 for January 1st.

isdst#
isdst: boolean

Whether daylight saving time is in effect where the time was interpreted.

LuaFile interface#

local interface LuaFile
    close: nosuspend function(self: LuaFile): (boolean?, string?)
    flush: function(self: LuaFile): (boolean?, string?)
    lines: function(self: LuaFile, ...: any): nosuspend function(): any
    read: function(self: LuaFile, ...: any): any
    seek: function(self: LuaFile, whence: string?, offset: number?): (number?, string?)
    setvbuf: function(self: LuaFile, mode: string, size: number?): (boolean?, string?)
    write: function(self: LuaFile, ...: any): (LuaFile?, string?)
end

A Lua file handle. Ownership is attached by producers rather than this interface, so standard streams and borrowed handles use the same type.

Methods#

close#
close: nosuspend function(self: LuaFile): (boolean?, string?)
Arguments#
Name Type Description
self LuaFile
Returns#
Type Description
boolean?
string?

flush#
flush: function(self: LuaFile): (boolean?, string?)
Arguments#
Name Type Description
self LuaFile
Returns#
Type Description
boolean?
string?

lines#
lines: function(self: LuaFile, ...: any): nosuspend function(): any
Arguments#
Name Type Description
self LuaFile
... any
Returns#
Type Description
nosuspend function(): any

read#
read: function(self: LuaFile, ...: any): any
Arguments#
Name Type Description
self LuaFile
... any
Returns#
Type Description
any

seek#
seek: function(self: LuaFile, whence: string?, offset: number?): (number?, string?)
Arguments#
Name Type Description
self LuaFile
whence string?
offset number?
Returns#
Type Description
number?
string?

setvbuf#
setvbuf: function(self: LuaFile, mode: string, size: number?): (boolean?, string?)
Arguments#
Name Type Description
self LuaFile
mode string
size number?
Returns#
Type Description
boolean?
string?

write#
write: function(self: LuaFile, ...: any): (LuaFile?, string?)
Arguments#
Name Type Description
self LuaFile
... any
Returns#
Type Description
LuaFile?
string?

Reflection#

What the compiler hands a program about a reified struct's memory. layoutof answers with a Layout; semantic descriptors instead live with the callable nupp.reflect namespace. Layout types sit apart from the types above because reading them is metaprogramming rather than calling a library.

Layout interface#

local interface Layout
    name: string
    size: integer
    alignment: integer
    fingerprint: string
    fields: {LayoutField}
end

How a reified struct is laid out, as layoutof answers it.

Every number here is this platform's: sizes and offsets come from the FFI at load rather than being baked in, because padding depends on the target. The fingerprint therefore describes one platform's layout, which is what makes it usable for detecting that saved data no longer matches.

Fields#

name#
name: string

The declaration's name.

size#
size: integer

Bytes one instance occupies, padding included.

alignment#
alignment: integer

Required byte alignment of the complete struct.

fingerprint#
fingerprint: string

A canonical description of the fields and the size, for detecting drift between the layout that wrote data and the layout reading it.

fields#

The fields, in declaration order.

LayoutField interface#

local interface LayoutField
    name: string
    ctype: string
    offset: integer
    size: integer
    alignment: integer
    padding: integer
end

One field of a reified struct, as it is actually laid out in C memory.

size is the field's own, from its C type. padding is what follows it before the next field starts, or before the struct ends. They are separate because they answer different questions: a reader wants the size, and a writer walking bytes has to know about the gap. An int8 before a number has size 1 and padding 7.

Fields#

name#
name: string

The field's name, as the declaration spells it.

ctype#
ctype: string

Its C type, as the generated ffi.typeof spells it.

offset#
offset: integer

Bytes from the start of the struct.

size#
size: integer

Bytes the field itself occupies.

alignment#
alignment: integer

Required byte alignment of the field's C type.

padding#
padding: integer

Bytes of alignment padding after it.