⌂ Modules LuaJIT standard library
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.
assertfunction
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
Arguments
takes v
T?
the value to test
msg
any?
the error to raise, "assertion failed!" by default
Returns
T preserves v
v, now known not to be nil or false
collectgarbagefunction
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
opt
`'collect'
'stop'
arg
number?
the step size or parameter that the operation takes
Returns
number
what the operation reports: "count" gives the kilobytes in use, while "step" and "isrunning" answer a boolean
dofilefunction
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
path
string?
the file to run, or nil for standard input
Returns
any
whatever the chunk returns
errorfunction
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
msg
any
the error value to raise
level
number?
whose position to blame, or 0 for none
Returns
gcinfofunction
local gcinfo : function ( ) : integer
Returns the amount of memory in use, in kilobytes. Superseded by collectgarbage("count").
Returns
integer
the kilobytes currently allocated
getfenvfunction
local getfenv : function ( f : any ? ) : table
Returns the environment a function sees as its globals, addressed the way setfenv addresses one.
Arguments
f
any?
the function to ask about, or a stack level
Returns
table
that function's globals
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
Arguments
Returns
metatable\<T\>?
the metatable, its __metatable stand-in, or nil
ipairsfunction
const ipairs : @ nosuspend function < V > ( borrows t : const { V } ) : @ nosuspend function ( ) : ( ( integer , V ) | ( nil ) ) borrows ( t )
Returns an iterator over the array part of t, from index 1 up to the first missing element.
when done
Type parameters
Arguments
borrows t
const{V}
the array to traverse
Returns
`@nosuspend function(): ((integer, V)
(nil)) borrows (t)`
loadfunction
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
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
any
the compiled chunk, or nil when it does not compile
string?
the compile error, when there was one
loadfilefunction
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
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
any
the compiled chunk, or nil when it does not load
string?
the load error, when there was one
loadstringfunction
local loadstring : function ( s : string , name : string ? ) : ( any , string ? )
Compiles the string s as a chunk, without running it.
Arguments
s
string
the source to compile
name
string?
the chunk name to use in error messages
Returns
any
the compiled chunk, or nil when it does not compile
string?
the compile error, when there was one
newproxyfunction
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
mt
any?
true for a new metatable, false or nil for none, or a proxy to share a metatable with
Returns
userdata
the new userdata
nextfunction
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
t
table
the table to step through
k
any?
the key to step past, or nil to start the traversal
Returns
any
the next key, or nil once the traversal is done
any
the value stored at that key
pairsfunction
local pairs : @ nosuspend function < K , V > (
borrows t : { @ readonly [ K ] : V }
) : @ nosuspend function ( ) : ( ( K , V ) | ( nil ) ) borrows ( t )
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
K
the key type
V
the value type
Arguments
borrows t
{@readonly \[K\]: V}
the table to traverse
Returns
`@nosuspend function(): ((K, V)
(nil)) borrows (t)`
pcallfunction
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
Arguments
scoped f
function(A...): R...
the function to call
?
A...
Returns
`((true, R...)
(false, unknown))`
printfunction
local print : @ nosuspend function ( borrows ... : any )
Writes every argument to standard output, converted with tostring, separated by tabs and followed by a newline.
Arguments
rawequalfunction
local rawequal : @ nosuspend function ( borrows a : any , borrows b : any ) : boolean
Compares two values for primitive equality, without an __eq metamethod.
Arguments
borrows a
any
the left value
borrows b
any
the right value
Returns
boolean
whether the values are primitively equal
rawgetfunction
local rawget : @ nosuspend function ( t : table , k : any ) : any
Reads t[k] without consulting an __index metamethod.
Arguments
t
table
the table to read
k
any
the key to read
Returns
any
the stored value, or nil when the key is absent
rawlenfunction
local rawlen : @ nosuspend function ( borrows v : any ) : integer
Returns the length of a table or string without consulting a __len metamethod.
Arguments
borrows v
any
the table or string to measure
Returns
rawsetfunction
local rawset : @ nosuspend function ( t : table , k : any , v : any ) : table
Assigns t[k] = v without consulting a __newindex metamethod.
Arguments
t
table
the table to write to
k
any
the key to write
v
any
the value to store
Returns
requirefunction
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 returns unknown in a Nupp file. The any declared here is what a plain Lua file gets for a computed name, and what any call through a shadowing binding gets.
Arguments
name
string
the module name, with . separating path components
Returns
any
the value the module returned
selectfunction
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
Arguments
n
'#'
the 1-based index to select from, or the string "#"
?
A...
Returns
integer
the selected arguments, or their count
setfenvfunction
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
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
any
f, when it was a 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
Arguments
takes t
T
the table to change
mt
metatable\<T\>?
the new metatable, or nil to remove the current one
Returns
tonumberfunction
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
v
any
the value to convert
base
number?
the numeral base, 2 through 36; decimal when omitted
Returns
number?
the number, or nil when v does not denote one
tostringfunction
local tostring : @ nosuspend function ( borrows v : any ) : string
Converts a value to a string, honoring a __tostring metamethod.
Arguments
borrows v
any
the value to convert
Returns
string
the string form of v
typefunction
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
borrows v
any
the value to classify
Returns
`"nil"
"boolean"
"number"
"string"
"table"
"function"
"thread"
"userdata"
"cdata"`
the type name
unpackfunction
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
Arguments
t
const{T}
the array to expand
i
number?
the first index, 1 by default
j
number?
the last index, #t by default
Returns
...T
the selected elements
xpcallfunction
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
Arguments
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...
Returns
`((true, R...)
(false, E))`
argvariable
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.bytefunction
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
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
Returns
...integer
one code per selected character
string.charfunction
local char : @ nosuspend function ( ... : number ) : string
Builds a string from the given character codes.
Arguments
...
number
the character codes, each 0 through 255
Returns
string
the assembled string
string.dumpfunction
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 a function compare equal across processes.
Arguments
f
any
the function to dump
strip
`(boolean
string)?`
Returns
string
the bytecode string
string.findfunction
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
Arguments
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
Returns
unpackof \_\_NuppFindResults(Pattern, Plain)
the index where the match starts, or nil when there is none
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
Arguments
fmt
Format
the format string
...
unpackof \_\_NuppFormatArguments(Format, nupp.Debug)
the values that the directives consume
Returns
string
the formatted string
string.gmatchfunction
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
Arguments
s
string
the string to scan
pat
Pattern
the pattern to repeat across s
Returns
`function(): ((unpackof __NuppGmatchResults(Pattern))
(nil))`
string.gsubfunction
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
Arguments
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
Returns
unpackof \_\_NuppGsubResults(Pattern)
the string with the replacements applied
string.lenfunction
local len : @ nosuspend function ( s : string ) : integer
Returns the length of s in bytes.
Arguments
s
string
the string to measure
Returns
string.lowerfunction
local lower : @ nosuspend function ( s : string ) : string
Returns s with every ASCII letter folded to lower case.
Arguments
s
string
the string to fold
Returns
string
the lowercased string
string.matchfunction
Returns the captures of the first match of pat in s, or the whole match when the pattern has no captures.
Type parameters
Arguments
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
Returns
unpackof \_\_NuppMatchResults(Pattern)
the captures or the whole match, or nil when nothing matches
string.repfunction
local rep : @ nosuspend function ( s : string , n : number , sep : string ? ) : string
Returns n copies of s, with sep between consecutive copies.
Arguments
s
string
the string to repeat
n
number
how many copies to produce
sep
string?
what to place between copies, nothing by default
Returns
string
the repeated string
string.reversefunction
local reverse : @ nosuspend function ( s : string ) : string
Returns the bytes of s in reverse order.
Arguments
s
string
the string to reverse
Returns
string
the reversed string
string.subfunction
local sub : @ nosuspend function ( s : string , i : number , j : number ? ) : string
Returns the substring of s running from i through j.
Arguments
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
string
the selected substring
string.upperfunction
local upper : @ nosuspend function ( s : string ) : string
Returns s with every ASCII letter folded to upper case.
Arguments
s
string
the string to fold
Returns
string
the uppercased string
table
Table manipulation. These functions work on the array part of a table: the integer keys 1 through #t.
table.clearfunction
@readonly
Removes every key from t while keeping the space it has already allocated, so it can be refilled without reallocating.
Arguments
t
table
the table to empty
table.clonefunction
local clone : @ nosuspend function < T is table > ( t : T ) : T
@readonly
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
Arguments
Returns
T
a new table holding the same keys, values and metatable
table.concatfunction
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
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
table.maxnfunction
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
t
table
the table to scan
Returns
number
the largest positive numeric key
table.newfunction
local new : function ( narray : number , nhash : number ) : table
@readonly
Creates a table preallocated for narray array slots and nhash hash slots, so filling it in does not have to rehash.
Arguments
narray
number
how many array slots to reserve
nhash
number
how many hash slots to reserve
Returns
table.removefunction
local remove : @ nosuspend function ( t : table , pos : number ? ) : any
Removes the element at pos, shifting later elements down.
Arguments
t
table
the array to remove from
pos
number?
the position to remove, #t by default
Returns
any
the element that was removed
table.sortfunction
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
Arguments
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.insertvariable
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.absfunction
local abs : @ nosuspend function ( x : number ) : number
Returns the absolute value of x.
Arguments
x
number
the number to take the magnitude of
Returns
number
the absolute value
math.acosfunction
local acos : @ nosuspend function ( x : number ) : number
Returns the arc cosine of x, in radians.
Arguments
x
number
the cosine to invert, -1 through 1
Returns
number
the angle in radians
math.asinfunction
local asin : @ nosuspend function ( x : number ) : number
Returns the arc sine of x, in radians.
Arguments
x
number
the sine to invert, -1 through 1
Returns
number
the angle in radians
math.atanfunction
local atan : @ nosuspend function ( x : number ) : number
Returns the arc tangent of x, in radians.
Arguments
x
number
the tangent to invert
Returns
number
the angle in radians
math.atan2function
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
y
number
the numerator
x
number
the denominator
Returns
number
the angle in radians
math.ceilfunction
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
x
number
the number to round up
Returns
integer
the rounded value
math.cosfunction
local cos : @ nosuspend function ( x : number ) : number
Returns the cosine of x, which is in radians.
Arguments
x
number
the angle in radians
Returns
math.coshfunction
local cosh : @ nosuspend function ( x : number ) : number
Returns the hyperbolic cosine of x.
Arguments
Returns
number
the hyperbolic cosine
math.degfunction
local deg : @ nosuspend function ( r : number ) : number
Converts the angle r from radians to degrees.
Arguments
r
number
the angle in radians
Returns
number
the angle in degrees
math.expfunction
local exp : @ nosuspend function ( x : number ) : number
Returns e raised to the power x.
Arguments
Returns
math.floorfunction
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
x
number
the number to round down
Returns
integer
the rounded value
math.fmodfunction
local fmod : @ nosuspend function ( x : number , y : number ) : number
Returns the remainder of x / y, keeping the sign of x.
Arguments
x
number
the dividend
y
number
the divisor
Returns
math.frexpfunction
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
x
number
the number to split
Returns
number
the fraction
number
the exponent
math.ldexpfunction
local ldexp : @ nosuspend function ( m : number , e : number ) : number
Returns m times 2 raised to the power e.
Arguments
m
number
the mantissa
e
number
the exponent
Returns
math.logfunction
local log : @ nosuspend function ( x : number , base : number ? ) : number
Returns the natural logarithm of x, or its logarithm in base.
Arguments
x
number
the number to take the logarithm of
base
number?
the base to use, e by default
Returns
math.maxfunction
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
Arguments
...
N
the numbers to compare, at least one
Returns
math.minfunction
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
Arguments
...
N
the numbers to compare, at least one
Returns
math.modffunction
local modf : @ nosuspend function ( x : number ) : ( number , number )
Splits x into its integral and fractional parts, both keeping the sign of x.
Arguments
x
number
the number to split
Returns
number
the integral part
number
the fractional part
math.powfunction
local pow : @ nosuspend function ( x : number , y : number ) : number
Returns x raised to the power y, the same as x ^ y.
Arguments
x
number
the base
y
number
the exponent
Returns
math.radfunction
local rad : @ nosuspend function ( d : number ) : number
Converts the angle d from degrees to radians.
Arguments
d
number
the angle in degrees
Returns
number
the angle in radians
math.randomfunction
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
m
number
the upper bound, or the lower bound when n is given too
n
number
the upper bound
Returns
number
the generated number
math.randomseedfunction
local randomseed : @ nosuspend function ( seed : number )
Seeds the pseudo-random generator, which starts from a fixed state.
Arguments
seed
number
the seed to start from
math.sinfunction
local sin : @ nosuspend function ( x : number ) : number
Returns the sine of x, which is in radians.
Arguments
x
number
the angle in radians
Returns
math.sinhfunction
local sinh : @ nosuspend function ( x : number ) : number
Returns the hyperbolic sine of x.
Arguments
Returns
number
the hyperbolic sine
math.sqrtfunction
local sqrt : @ nosuspend function ( x : number ) : number
Returns the square root of x.
Arguments
x
number
the number to take the root of
Returns
math.tanfunction
local tan : @ nosuspend function ( x : number ) : number
Returns the tangent of x, which is in radians.
Arguments
x
number
the angle in radians
Returns
math.tanhfunction
local tanh : @ nosuspend function ( x : number ) : number
Returns the hyperbolic tangent of x.
Arguments
Returns
number
the hyperbolic tangent
math.hugevariable
Positive infinity, which compares greater than any other number.
math.pivariable
The ratio of a circle's circumference to its diameter.
os
Operating-system facilities: clocks and calendars, the environment, processes and file names.
os.clockfunction
local clock : function ( ) : number
Returns the CPU time the program has used, in seconds. It measures intervals of work, not wall-clock time.
Returns
number
the CPU seconds consumed so far
os.datefunction
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 returns: "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
Arguments
fmt
Format?
the strftime format, "%c" by default
t
number?
the time to format, the current time by default
Returns
\_\_NuppDateResult(Format, DateFields)
the formatted string, or the field table for "*t"
os.difftimefunction
local difftime : function ( t2 : number , t1 : number ) : number
Returns the number of seconds from t1 to t2.
Arguments
t2
number
the later time
t1
number
the earlier time
Returns
number
the difference in seconds
os.executefunction
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
cmd
string?
the command line to run
Returns
any
the command's exit status, or whether a shell exists
os.exitfunction
local exit : function ( code : any ? ) : never
Ends the process, closing the interpreter state on the way out.
Arguments
code
any?
the exit status: true or 0 for success, false or another number for failure
Returns
os.getenvfunction
local getenv : function ( name : string ) : string ?
Returns the value of the environment variable name.
Arguments
name
string
the variable to read
Returns
string?
its value, or nil when it is not set
os.removefunction
local remove : function ( path : string ) : ( boolean ? , string ? )
Deletes the file, or the empty directory, at path.
Arguments
path
string
what to delete
Returns
boolean?
true on success, or nil on failure
string?
the reason it failed
os.renamefunction
local rename : function ( from : string , to : string ) : ( boolean ? , string ? )
Renames the file or directory at from to to.
Arguments
from
string
the existing path
to
string
the new path
Returns
boolean?
true on success, or nil on failure
string?
the reason it failed
os.timefunction
local time : function ( spec : table ? ) : number
Returns the current time, or the time that spec describes.
Arguments
spec
table?
a table with year, month and day, and optionally hour, min, sec and isdst
Returns
number
the time, in the system's own epoch-based encoding
os.tmpnamefunction
local tmpname : function ( ) : string
Returns a file name usable for a temporary file. The file itself is neither created nor removed for you.
Returns
string
the temporary file name
package
package.loadlibfunction
local loadlib : function ( path : string , symbol : string ) : ( any , string ? )
Opens a shared object and returns the named C entry point, or nil and why when it could not be opened.
Arguments
path
string
symbol
string
Returns
package.configvariable
Platform path separators and template markers.
package.cpathvariable
Search templates used by require for C modules.
package.loadedvariable
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.loadersvariable
local loaders : { function ( string ) : any }
Lua 5.1 and Lua 5.2 names for the module-loader chain.
package.pathvariable
Search templates used by require for Lua modules.
package.preloadvariable
local preload : { [ string ] : function ( ... : any ) : any }
Modules made available without consulting the filesystem.
package.searchersvariable
local searchers : { function ( string ) : any } ?
io
io.closefunction
Closes f, or the default output file when it is omitted.
Arguments
f
LuaFile?
the file to close
Returns
boolean?
whether the file closed cleanly
Sets the default input file, opening f first when it is a name. With no argument it returns the current one instead.
Arguments
Returns
LuaFile
the default input file
io.linesfunction
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
path
string?
the file to read, or nil for the default input file
Returns
@nosuspend function(): string?
an iterator yielding one line at a time, and nil once the file is read
io.openfunction
Opens the file at path. Modes are "r", "w" and "a", with "+" added for update and a trailing "b" for binary.
Arguments
path
string
the file to open
mode
string?
the mode to open it in, "r" by default
Returns
affine(LuaFile, \_)?
the file handle, or nil when it cannot be opened
string?
the reason it could not be opened
io.outputfunction
Sets the default output file, opening f first when it is a name. With no argument it returns the current one instead.
Arguments
Returns
LuaFile
the default output file
io.popenfunction
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
cmd
string
the command line to run
mode
string?
which stream to connect, "r" by default
Returns
affine(LuaFile, \_)?
the file handle, or nil when the process cannot start
string?
the reason it could not start
io.readfunction
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
...
any
the formats to read, "*l" by default
Returns
any
one value per format, or nil where the read came up short
io.tmpfilefunction
Opens a temporary file in update mode, removed when the program ends.
Returns
affine(LuaFile, \_)?
the file handle
io.writefunction
local write : function ( ... : any ) : any
Writes each argument, which must be a string or a number, to the default output file.
Arguments
...
any
the values to write
Returns
any
the file that was written to
io.stderrvariable
The standard error stream.
io.stdinvariable
The standard input stream.
io.stdoutvariable
The standard output stream.
io.typevariable
local type : @ nosuspend function ( value : any ) : ( "file" | "closed file" ) ?
Classifies an open or closed file handle.
coroutine
coroutine.createfunction
Creates a coroutine with f as its body. The body does not start running until the first resume.
Arguments
f
any
the function to run inside the coroutine
Returns
coroutine.isyieldablefunction
local isyieldable : function ( ) : boolean
Whether the running coroutine is allowed to yield, which is false on the main coroutine.
Returns
boolean
whether a yield would succeed here
coroutine.resumefunction
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
Arguments
co
thread
the coroutine to run
?
A...
Returns
...any
true when it yielded or returned, false when it raised
coroutine.runningfunction
local running : function ( ) : ( thread ? , boolean )
Returns the coroutine that is running.
Returns
thread?
the running coroutine
boolean
whether that is the main coroutine
coroutine.statusfunction
local status : function ( co : thread ) : string
Returns the state of co: "running", "suspended", "normal" for one that resumed another coroutine, or "dead".
Arguments
co
thread
the coroutine to inspect
Returns
coroutine.wrapfunction
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
f
any
the function to run inside the coroutine
Returns
any
a function that resumes the coroutine
coroutine.yieldfunction
local yield : function < Y ... > ( Y ... ) : ... any
Suspends the running coroutine. The arguments become the results of the resume that started it.
Type parameters
Arguments
Returns
...any
the values passed to the next resume
bit
Nupp provides access to LuaJIT's BitOp library, which every target has.
const bit = require ( "bit" )
print ( bit . tohex ( bit . bswap ( 0x11223344 ) ) )
print ( bit . rol ( 0xFF , 8 ) )
print ( 0xF0 & 0x3C )
bit.arshiftfunction
local arshift : @ nosuspend function ( x : number , n : number ) : integer
Shifts x right by n bits, copying the sign bit down.
Arguments
x
number
the number to shift
n
number
how many bits to shift by, taken modulo 32
Returns
integer
the shifted value
bit.bandfunction
local band : @ nosuspend function ( x : number , ... : number ) : integer
Returns the bitwise and of x and every remaining argument.
Arguments
x
number
the first number to combine
...
number
the remaining numbers to combine
Returns
integer
the combined value
bit.bnotfunction
local bnot : @ nosuspend function ( x : number ) : integer
Returns the bitwise complement of x.
Arguments
x
number
the number to complement
Returns
bit.borfunction
local bor : @ nosuspend function ( x : number , ... : number ) : integer
Returns the bitwise or of x and every remaining argument.
Arguments
x
number
the first number to combine
...
number
the remaining numbers to combine
Returns
integer
the combined value
bit.bswapfunction
local bswap : @ nosuspend function ( x : number ) : integer
Swaps the byte order of x, converting between endiannesses.
Arguments
x
number
the number to byte-swap
Returns
integer
the swapped value
bit.bxorfunction
local bxor : @ nosuspend function ( x : number , ... : number ) : integer
Returns the bitwise exclusive or of x and every remaining argument.
Arguments
x
number
the first number to combine
...
number
the remaining numbers to combine
Returns
integer
the combined value
bit.lshiftfunction
local lshift : @ nosuspend function ( x : number , n : number ) : integer
Shifts x left by n bits, filling with zeros.
Arguments
x
number
the number to shift
n
number
how many bits to shift by, taken modulo 32
Returns
integer
the shifted value
bit.rolfunction
local rol : @ nosuspend function ( x : number , n : number ) : integer
Rotates x left by n bits.
Arguments
x
number
the number to rotate
n
number
how many bits to rotate by, taken modulo 32
Returns
integer
the rotated value
bit.rorfunction
local ror : @ nosuspend function ( x : number , n : number ) : integer
Rotates x right by n bits.
Arguments
x
number
the number to rotate
n
number
how many bits to rotate by, taken modulo 32
Returns
integer
the rotated value
bit.rshiftfunction
local rshift : @ nosuspend function ( x : number , n : number ) : integer
Shifts x right by n bits without sign extension.
Arguments
x
number
the number to shift
n
number
how many bits to shift by, taken modulo 32
Returns
integer
the shifted value
bit.tobitfunction
local tobit : @ nosuspend function ( x : number ) : integer
Normalizes x into the signed 32-bit integer range, wrapping around.
Arguments
x
number
the number to normalize
Returns
integer
the normalized value
bit.tohexfunction
local tohex : @ nosuspend function ( x : number , n : number ? ) : string
Returns x in hexadecimal, using n digits.
Arguments
x
number
the number to convert
n
number?
how many digits to print, 8 by default; a negative count prints uppercase digits
Returns
string
the hexadecimal text
jit
jit.attachfunction
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
callback
function(...: any)
the handler to add, or the one to remove
event
string?
which event to attach to, or nil to detach
jit.flushfunction
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
f
any?
the function to flush, a trace number, or nil for the whole cache
recursive
boolean?
whether to flush nested functions too
jit.offfunction
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
f
any?
the function to disable, or nil for the whole VM
recursive
boolean?
whether to apply the change to nested functions too
jit.onfunction
local on : function ( f : any ? , recursive : boolean ? )
Turns compilation on for f, or for the whole VM when it is omitted.
Arguments
f
any?
the function to enable, or nil for the whole VM
recursive
boolean?
whether to apply the change to nested functions too
jit.securityfunction
local security : function ( param : string ) : any
Reports how the VM was built for a security-relevant parameter, such as "prng" or "strhash".
Arguments
param
string
the parameter to report on
Returns
jit.statusfunction
local status : function ( ) : ( boolean , any )
Reports whether the compiler is enabled.
Returns
boolean
whether compilation is currently on
any
the optimization flags in force, one per result
jit.archvariable
The target architecture, such as "x64" or "arm64".
jit.optvariable
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.osvariable
The operating system, such as "Linux", "OSX" or "Windows".
jit.versionvariable
The LuaJIT version string, such as "LuaJIT 2.1.0".
jit.version_numvariable
local version_num : number
The LuaJIT version as a number, where 2.1.0 reads as 20100.
debug
debug.gethookfunction
local gethook : function ( ) : any
Returns the hook currently installed.
Returns
any
the hook function, its mask and its count
debug.getinfofunction
local getinfo : function ( f : any , what : string ? ) : any
Describes a function, or the activation record at a stack level.
Arguments
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
any
the description table, or nil when the level is out of range
debug.getlocalfunction
local getlocal : function ( level : any , idx : number ) : ( string ? , any )
Reads local variable idx of the function at a stack level.
Arguments
level
any
the stack level, or a function to inspect
idx
number
the 1-based index of the local
Returns
string?
the variable's name, or nil past the last one
any
its current value
local getmetatable : function ( v : any ) : table ?
Returns the metatable of v, ignoring any __metatable field.
Arguments
v
any
the value to inspect
Returns
table?
the metatable, or nil when there is none
debug.getregistryfunction
local getregistry : function ( ) : table
Returns the registry, the table where C code anchors its references.
Returns
debug.getupvaluefunction
local getupvalue : function ( f : any , idx : number ) : ( string ? , any )
Reads upvalue idx of the function f.
Arguments
f
any
the function to inspect
idx
number
the 1-based index of the upvalue
Returns
string?
the upvalue's name, or nil past the last one
any
its current value
debug.sethookfunction
local sethook : function ( ... : any )
Installs a debug hook: a function, a mask built from "c", "r" and "l", and an optional instruction count.
Arguments
...
any
the hook function, its mask, and the count
debug.setlocalfunction
local setlocal : function ( level : any , idx : number , v : any ) : string ?
Assigns v to local variable idx at a stack level.
Arguments
level
any
the stack level to write into
idx
number
the 1-based index of the local
v
any
the value to store
Returns
string?
the variable's name, or nil past the last one
local setmetatable : function ( v : any , mt : table ? ) : any
Sets v's metatable, ignoring any __metatable field.
Arguments
v
any
the value to change
mt
table?
the new metatable, or nil to remove the current one
Returns
debug.setupvaluefunction
local setupvalue : function ( f : any , idx : number , v : any ) : string ?
Assigns v to upvalue idx of the function f.
Arguments
f
any
the function to modify
idx
number
the 1-based index of the upvalue
v
any
the value to store
Returns
string?
the upvalue's name, or nil past the last one
debug.tracebackfunction
local traceback : function ( msg : any ? , level : number ? ) : string
Returns a traceback of the call stack, with msg at the front.
Arguments
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
string
the traceback text
debug.upvaluejoinfunction
local upvaluejoin : function ( f : any , idx : number , source : any , sourceIdx : number )
Makes a function's upvalue refer to the same lexical cell as another's.
Arguments
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.ffirecord
Members
string
method
Copies a C string (or len bytes) into a Lua string.
new
method
Allocates a cdata object of the given type.
typeof
method
Returns the ctype object for a C type declaration.
cast
method
Reinterprets a value as another C type.
metatype
method
Associates a metatable with a ctype; returns the ctype.
gc
method
Attaches a finalizer to a cdata object; returns the object.
istype
method
True when obj has the given ctype.
sizeof
method
Size in bytes, or nil for incomplete types.
alignof
method
Alignment in bytes.
offsetof
method
Byte offset of a struct field.
copy
method
Bulk copy between cdata (or from a Lua string).
fill
method
Fills memory with a byte value (zero by default).
cdef
method
Adds C declarations to the global C namespace.
load
method
Loads a shared library and returns its namespace.
abi
method
True when the ABI parameter holds (e.g.
errno
method
Reads, and optionally sets, the C errno.
typeinfo
method
Reads LuaJIT's own record of a declared C type.
C
field
The default C namespace: symbols in the running process.
os
field
arch
field
stringmethod
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
ptr
any
len
`(integer
int64
Returns
newmethod
new : function ( ct : any , ... : any ) : any
Allocates a cdata object of the given type.
Arguments
Returns
typeofmethod
typeof : function ( ct : any , ... : any ) : any
Returns the ctype object for a C type declaration.
Arguments
Returns
castmethod
cast : function ( ct : any , value : any ) : any
Reinterprets a value as another C type.
Arguments
Returns
metatype : function ( ct : any , mt : table ) : any
Associates a metatable with a ctype; returns the ctype.
Arguments
Returns
gcmethod
gc : function ( obj : any , finalizer : any ) : any
Attaches a finalizer to a cdata object; returns the object.
Arguments
Returns
istypemethod
istype : function ( ct : any , obj : any ) : boolean
True when obj has the given ctype.
Arguments
Returns
sizeofmethod
sizeof : function ( ct : any , nelem : integer ? ) : integer ?
Size in bytes, or nil for incomplete types.
Arguments
Returns
alignofmethod
alignof : function ( ct : any ) : integer
Alignment in bytes.
Arguments
Returns
offsetofmethod
offsetof : function ( ct : any , field : string ) : integer ?
Byte offset of a struct field.
Arguments
Returns
copymethod
copy : function ( borrows dst : any , borrows src : any , len : ( integer | int64 | uint64 ) ? )
Bulk copy between cdata (or from a Lua string).
Arguments
borrows dst
any
borrows src
any
len
`(integer
int64
fillmethod
fill : function ( dst : any , len : integer | int64 | uint64 , c : integer ? )
Fills memory with a byte value (zero by default).
Arguments
dst
any
len
`integer
int64
c
integer?
cdefmethod
cdef : function ( def : string )
Adds C declarations to the global C namespace.
Arguments
loadmethod
load : function ( name : string , global : boolean ? ) : any
Loads a shared library and returns its namespace.
Arguments
name
string
global
boolean?
Returns
abimethod
abi : function ( param : string ) : boolean
True when the ABI parameter holds (e.g. "64bit", "le").
Arguments
Returns
errnomethod
errno : function ( newerr : integer ? ) : integer
Reads, and optionally sets, the C errno.
Arguments
Returns
typeinfomethod
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
Returns
Cfield
The default C namespace: symbols in the running process.
osfield
archfield
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.decodefunction
local decode : function ( s : string ) : any
Deserializes a whole encoded string. Raises on malformed input, and also when anything is left over after a top-level object.
Arguments
s
string
the encoded bytes
Returns
any
the decoded value, of any supported type
string.buffer.encodefunction
local encode : function ( v : any ) : string
Serializes v to a string. Raises on unsupported types, circular references, and nesting too deep to encode.
Arguments
v
any
the value to serialize
Returns
string.buffer.newfunction
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
size
`(integer
table)?`
options
table?
the serialization options
Returns
string.buffer.Bufferrecord
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.
Members
\_\_len
metamethod
\_\_concat
metamethod
\_\_tostring
metamethod
put
method
Appends each argument: a string, a number, another buffer, or any object with a tostring metamethod.
putf
method
Appends the arguments formatted by fmt, which takes the same directives as string.format.
putcdata
method
Appends len bytes read from the memory that data points to.
set
method
Replaces the buffer contents with a reference to data, freeing any space already allocated.
get
method
Consumes bytes from the front of the buffer and returns them.
tostring
method
Returns the buffer contents as a string, without consuming them.
reset
method
Empties the buffer, keeping the space it has already allocated so it can be refilled without reallocating.
free
method
Frees the buffer space at once, leaving the object itself intact and empty.
skip
method
Consumes n bytes from the front of the buffer and discards them, stopping at the end of the data.
ref
method
Returns a pointer to the buffer data, for zero-copy reads and in-place writes.
reserve
method
Reserves at least size bytes of write space and returns a pointer to it.
commit
method
Appends the first used bytes of the space handed out by the last reserve to the buffer data.
encode
method
Serializes obj and appends the encoding to the buffer.
decode
method
Deserializes an object from the front of the buffer, leaving any data after it in place.
__len : function ( self ) : integer
Arguments
Returns
__concat : function ( self , other : any ) : string
Arguments
Returns
__tostring : function ( self ) : string
Arguments
Returns
putmethod
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
exclusive b
Buffer
the buffer to append to
...
any
the values to append, in order
Returns
putfmethod
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
exclusive b
Buffer
the buffer to append to
fmt
string
the format string
...
any
the values that the directives consume
Returns
putcdatamethod
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
exclusive b
Buffer
the buffer to append to
data
voidptr
the memory to copy from
len
integer
how many bytes to copy
Returns
setmethod
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
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
getmethod
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
exclusive b
Buffer
the buffer to read from
...
integer?
how many bytes each returned string takes
Returns
string
one string per argument, or the whole buffer when given none
tostringmethod
tostring : function ( b : Buffer ) : string
Returns the buffer contents as a string, without consuming them.
Arguments
b
Buffer
the buffer to read
Returns
string
the buffer contents
resetmethod
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
exclusive b
Buffer
the buffer to empty
Returns
freemethod
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
exclusive b
Buffer
the buffer to free
Returns
skipmethod
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
exclusive b
Buffer
the buffer to skip in
n
integer
how many bytes to discard
Returns
refmethod
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
borrows b
Buffer
the buffer to point into
Returns
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
reservemethod
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
exclusive b
Buffer
the buffer to reserve space in
size
integer
how many bytes are needed at least
Returns
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
commitmethod
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
exclusive b
Buffer
the buffer that space was reserved in
used
integer
how many bytes were written
Returns
encodemethod
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
exclusive b
Buffer
the buffer to append to
obj
any
the value to serialize
Returns
decodemethod
decode : function ( exclusive b : Buffer ) : any
Deserializes an object from the front of the buffer, leaving any data after it in place. Raises on malformed or truncated input.
Arguments
exclusive b
Buffer
the buffer to read from
Returns
any
the decoded value, of any supported type
jit.util
Declarations for LuaJIT's jit.util module, loaded for require("jit.util").
Call require("jit.util"); LuaJIT registers the module only under package.loaded, not as a field on jit.
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 returns nil rather than raising. Treat the results as diagnostic output to print, not as data to compute with.
jit.util.JitUtilrecord
Members
funcinfo
method
Describes a function, or the bytecode position pc inside it.
funcbc
method
Reads a bytecode instruction.
funck
method
Reads a constant from a function's constant table.
funcuvname
method
Names an upvalue.
traceinfo
method
Describes a compiled trace: its link, extent, exit count, and the machine code it occupies.
traceir
method
Reads an IR instruction from a trace.
tracek
method
Reads a constant referenced by a trace's IR.
tracesnap
method
Reads a trace snapshot: the stack map an exit restores from.
tracemc
method
Returns a trace's machine code.
traceexitstub
method
Address of the exit stub for one of a trace's exits.
ircalladdr
method
Address of an IR call target, for naming a call in a disassembly.
funcinfomethod
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
func
any
the function to describe
pc
integer?
the bytecode index to resolve currentline from
Returns
{\[string\]: any}
a freshly allocated description table
funcbcmethod
funcbc : function ( func : any , pc : integer ) : ( integer ? , integer ? )
Reads a bytecode instruction.
Arguments
func
any
the function to read from
pc
integer
the bytecode index, counting from 0
Returns
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")
funckmethod
funck : function ( func : any , idx : integer ) : any
Reads a constant from a function's constant table.
Arguments
func
any
the function to read from
idx
integer
the constant index: non-negative for a number, negative for a garbage-collected constant
Returns
any
the constant, or nil when the index is out of range
funcuvnamemethod
funcuvname : function ( func : any , idx : integer ) : string ?
Names an upvalue.
Arguments
func
any
the function to read from
idx
integer
the upvalue index, counting from 0
Returns
string?
the name, or nil when the index is out of range
traceinfomethod
traceinfo : function ( tr : integer ) : { [ string ] : any } ?
Describes a compiled trace: its link, extent, exit count, and the machine code it occupies.
Arguments
tr
integer
the trace number
Returns
{\[string\]: any}?
the description table, or nil when no such trace exists
traceirmethod
traceir : function ( tr : integer , idx : integer ) : ( integer ? , integer ? , integer ? , integer ? , integer ? )
Reads an IR instruction from a trace.
Arguments
tr
integer
the trace number
idx
integer
the IR reference
Returns
integer?
the IR mode, the opcode and type byte, the two operands, and the previous reference in the chain, or five nil values when the trace or reference does not exist
integer?
integer?
integer?
integer?
tracekmethod
tracek : function ( tr : integer , idx : integer ) : ( any , integer ? , integer ? )
Reads a constant referenced by a trace's IR.
Arguments
tr
integer
the trace number
idx
integer
the IR reference of the constant
Returns
any
the constant value
integer?
its IR type, or nil when the trace or reference does not exist
integer?
the stack slot it was loaded from, when there was one
tracesnapmethod
tracesnap : function ( tr : integer , sn : integer ) : { [ string ] : any } ?
Reads a trace snapshot: the stack map an exit restores from.
Arguments
tr
integer
the trace number
sn
integer
the snapshot index
Returns
{\[string\]: any}?
the snapshot table, or nil when the index is out of range
tracemcmethod
tracemc : function ( tr : integer ) : ( string ? , integer ? , integer ? )
Returns a trace's machine code.
Arguments
tr
integer
the trace number
Returns
string?
the machine code as a byte string
integer?
the address it was assembled to run at
integer?
the loop offset within it
traceexitstubmethod
traceexitstub : function ( tr : integer , exitno : integer ) : integer ?
Address of the exit stub for one of a trace's exits.
Arguments
tr
integer
the trace number
exitno
integer
the exit number
Returns
integer?
the address, or nil when the exit does not exist
ircalladdrmethod
ircalladdr : function ( idx : integer ) : integer ?
Address of an IR call target, for naming a call in a disassembly.
Arguments
idx
integer
the index into the IR call table, which require("jit.vmdef").ircall names
Returns
integer?
the address, or nil when the index is out of range
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.JitProfilerecord
local record JitProfile ...
Members
start
method
Starts sampling, calling cb for each batch of samples.
stop
method
Stops the running profiler.
dumpstack
method
Renders a sampled stack as text.
startmethod
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
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
stopmethod
Stops the running profiler. Safe to call when none is running.
dumpstackmethod
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
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
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.Zonerecord
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.
Members
\_\_call
metamethod
Pushes name, or pops and returns the innermost zone when name is omitted.
flush
method
Discards every pushed zone, leaving the stack empty.
get
method
Returns the innermost zone without popping it.
__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
z
Zone
the zone stack
name
string?
the zone to push, or nil to pop
Returns
string?
the popped zone, when popping
flushmethod
Discards every pushed zone, leaving the stack empty.
Arguments
getmethod
get : function ( z : Zone ) : string ?
Returns the innermost zone without popping it.
Arguments
Returns
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.
DateFieldsinterface
local interface DateFields ...
The fields os.date("*t") returns.
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.
Members
year
field
The full year, not an offset from 1900.
month
field
The month, 1 through 12.
day
field
The day of the month, 1 through 31.
hour
field
The hour, 0 through 23.
min
field
The minute, 0 through 59.
sec
field
The second, 0 through 60, the last of which is a leap second.
wday
field
The day of the week, 1 for Sunday.
yday
field
The day of the year, 1 for January 1st.
isdst
field
Whether daylight saving time is in effect where the time was interpreted.
yearfield
The full year, not an offset from 1900.
monthfield
The month, 1 through 12.
dayfield
The day of the month, 1 through 31.
hourfield
The hour, 0 through 23.
minfield
The minute, 0 through 59.
secfield
The second, 0 through 60, the last of which is a leap second.
wdayfield
The day of the week, 1 for Sunday.
ydayfield
The day of the year, 1 for January 1st.
isdstfield
Whether daylight saving time is in effect where the time was interpreted.
LuaFileinterface
local interface LuaFile ...
A Lua file handle. Ownership is attached by producers rather than this interface, so standard streams and borrowed handles use the same type.
Members
closemethod
close : @ nosuspend function ( self : LuaFile ) : ( boolean ? , string ? )
Arguments
Returns
flushmethod
flush : function ( self : LuaFile ) : ( boolean ? , string ? )
Arguments
Returns
linesmethod
lines : function ( self : LuaFile , ... : any ) : @ nosuspend function ( ) : any
Arguments
Returns
@nosuspend function(): any
readmethod
Arguments
Returns
seekmethod
seek : function ( self : LuaFile , whence : string ? , offset : number ? ) : ( number ? , string ? )
Arguments
self
LuaFile
whence
string?
offset
number?
Returns
setvbufmethod
setvbuf : function ( self : LuaFile , mode : string , size : number ? ) : ( boolean ? , string ? )
Arguments
self
LuaFile
mode
string
size
number?
Returns
writemethod
Arguments
Returns
Reflection
What the compiler hands a program about a reified struct's memory. layoutof returns 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.
Layoutinterface
local interface Layout ...
How a reified struct is laid out, as layoutof returns 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.
Members
name
field
The declaration's name.
size
field
Bytes one instance occupies, padding included.
alignment
field
Required byte alignment of the complete struct.
fingerprint
field
A canonical description of the fields and the size, for detecting drift between the layout that wrote data and the...
fields
field
The fields, in declaration order.
namefield
The declaration's name.
sizefield
Bytes one instance occupies, padding included.
alignmentfield
Required byte alignment of the complete struct.
fingerprintfield
A canonical description of the fields and the size, for detecting drift between the layout that wrote data and the layout reading it.
fieldsfield
The fields, in declaration order.
LayoutFieldinterface
local interface LayoutField ...
A 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.
Members
name
field
The field's name, as the declaration spells it.
ctype
field
Its C type, as the generated ffi.typeof spells it.
offset
field
Bytes from the start of the struct.
size
field
Bytes the field itself occupies.
alignment
field
Required byte alignment of the field's C type.
padding
field
Bytes of alignment padding after it.
namefield
The field's name, as the declaration spells it.
ctypefield
Its C type, as the generated ffi.typeof spells it.
offsetfield
Bytes from the start of the struct.
sizefield
Bytes the field itself occupies.
alignmentfield
Required byte alignment of the field's C type.
paddingfield
Bytes of alignment padding after it.
← Previous Diagnostics Next → nupp