⌂ 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.
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
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
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
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
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
path
string?
the file to run, or nil for standard input
Returns
any
whatever the chunk returns
error function
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
gcinfo function
local gcinfo : function ( ) : integer
Returns the amount of memory in use, in kilobytes. Superseded by collectgarbage("count").
Returns
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
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
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
Arguments
borrows t
const{V}
the array to traverse
Returns
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
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
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
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
loadstring function
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
newproxy constructor
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
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
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
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
K
the key type
V
the value type
Arguments
t
{readonly \[K\]: V}
the table to traverse
Returns
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
Arguments
scoped f
function(A...): R...
the function to call
?
A...
print function
local print : nosuspend function ( borrows ... : any )
Writes every argument to standard output, converted with tostring, separated by tabs and followed by a newline.
Arguments
rawequal function
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
rawget function
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
rawlen function
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
rawset function
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
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
string
the module name, with . separating path components
Returns
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
Arguments
n
'#'
the 1-based index to select from, or the string "#"
?
A...
Returns
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
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
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
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
tostring function
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
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
borrows v
any
the value to classify
Returns
`"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
Arguments
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
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...
arg variable
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
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
...
number
the character codes, each 0 through 255
Returns
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
f
any
the function to dump
strip
`(boolean
string)?`
Returns
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
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
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.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
Arguments
s
string
the string to scan
pat
Pattern
the pattern to repeat across s
Returns
`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
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
string.len function
local len : nosuspend function ( s : string ) : integer
Returns the length of s in bytes.
Arguments
s
string
the string to measure
Returns
string.lower function
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.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
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
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
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.reverse function
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.sub function
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.upper function
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.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
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
Arguments
Returns
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
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.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
t
table
the table to scan
Returns
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
narray
number
how many array slots to reserve
nhash
number
how many hash slots to reserve
Returns
table.remove function
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.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
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.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
x
number
the number to take the magnitude of
Returns
number
the absolute value
math.acos function
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.asin function
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.atan function
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.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
y
number
the numerator
x
number
the denominator
Returns
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
x
number
the number to round up
Returns
integer
the rounded value
math.cos function
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.cosh function
local cosh : nosuspend function ( x : number ) : number
Returns the hyperbolic cosine of x.
Arguments
Returns
number
the hyperbolic cosine
math.deg function
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.exp function
local exp : nosuspend function ( x : number ) : number
Returns e raised to the power x.
Arguments
Returns
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
x
number
the number to round down
Returns
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
x
number
the dividend
y
number
the divisor
Returns
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
x
number
the number to split
Returns
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
m
number
the mantissa
e
number
the exponent
Returns
math.log function
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.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
Arguments
...
N
the numbers to compare, at least one
Returns
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
Arguments
...
N
the numbers to compare, at least one
Returns
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
x
number
the number to split
Returns
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
x
number
the base
y
number
the exponent
Returns
math.rad function
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.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
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.randomseed function
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.sin function
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.sinh function
local sinh : nosuspend function ( x : number ) : number
Returns the hyperbolic sine of x.
Arguments
Returns
number
the hyperbolic sine
math.sqrt function
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.tan function
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.tanh function
local tanh : nosuspend function ( x : number ) : number
Returns the hyperbolic tangent of x.
Arguments
Returns
number
the hyperbolic tangent
math.huge variable
Positive infinity, which compares greater than any other number.
math.pi variable
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
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
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.difftime function
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.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
cmd
string?
the command line to run
Returns
any
the command's exit status, or whether a shell exists
os.exit function
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.getenv function
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.remove function
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.rename function
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.time function
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.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
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
path
string
symbol
string
Returns
package.config variable
Platform path separators and template markers.
package.cpath variable
Search templates used by require for C modules.
package.loaded variable
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
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
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.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
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.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
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.output function
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.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
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.read function
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.tmpfile function
Opens a temporary file in update mode, removed when the program ends.
Returns
affine(LuaFile, \_)?
the file handle
io.write function
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.stderr variable
The standard error stream.
io.stdin variable
The standard input stream.
io.stdout variable
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
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.isyieldable function
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.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
Arguments
co
thread
the coroutine to run
?
A...
coroutine.running function
local running : function ( ) : ( thread ? , boolean )
Returns the coroutine that is running.
Returns
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
co
thread
the coroutine to inspect
Returns
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
f
any
the function to run inside the coroutine
Returns
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
Arguments
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
x
number
the number to shift
n
number
how many bits to shift by, taken modulo 32
Returns
integer
the shifted value
bit.band function
local band : nosuspend function ( ... : number ) : integer
Returns the bitwise and of every argument.
Arguments
...
number
the numbers to combine
Returns
integer
the combined value
bit.bnot function
local bnot : nosuspend function ( x : number ) : integer
Returns the bitwise complement of x.
Arguments
x
number
the number to complement
Returns
bit.bor function
local bor : nosuspend function ( ... : number ) : integer
Returns the bitwise or of every argument.
Arguments
...
number
the numbers to combine
Returns
integer
the combined value
bit.bswap function
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.bxor function
local bxor : nosuspend function ( ... : number ) : integer
Returns the bitwise exclusive or of every argument.
Arguments
...
number
the numbers to combine
Returns
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
x
number
the number to shift
n
number
how many bits to shift by, taken modulo 32
Returns
integer
the shifted value
bit.rol function
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.ror function
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.rshift function
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.tobit function
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.tohex function
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.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
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
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
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
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
param
string
the parameter to report on
Returns
jit.status function
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.arch variable
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
The operating system, such as "Linux", "OSX" or "Windows".
jit.version variable
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
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
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.getlocal function
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.getregistry function
local getregistry : function ( ) : table
Returns the registry, the table where C code anchors its references.
Returns
debug.getupvalue function
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.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
...
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
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.setupvalue function
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.traceback function
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.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
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
ptr
any
len
`(integer
int64
Returns
new
Allocates a cdata object of the given type.
Arguments
Returns
typeof
Returns the ctype object for a C type declaration.
Arguments
Returns
cast
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
gc
Attaches a finalizer to a cdata object; returns the object.
Arguments
Returns
istype
istype : function ( ct : any , obj : any ) : boolean
True when obj has the given ctype.
Arguments
Returns
sizeof
sizeof : function ( ct : any , nelem : integer ? ) : integer ?
Size in bytes, or nil for incomplete types.
Arguments
Returns
alignof
alignof : function ( ct : any ) : integer
Alignment in bytes.
Arguments
Returns
offsetof
offsetof : function ( ct : any , field : string ) : integer ?
Byte offset of a struct field.
Arguments
Returns
copy
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
fill
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?
cdef
cdef : function ( def : string )
Adds C declarations to the global C namespace.
Arguments
load
load : function ( name : string , global : boolean ? ) : any
Loads a shared library and returns its namespace.
Arguments
name
string
global
boolean?
Returns
abi
abi : function ( param : string ) : boolean
True when the ABI parameter holds (e.g. "64bit", "le").
Arguments
Returns
errno
errno : function ( newerr : integer ? ) : integer
Reads, and optionally sets, the C errno.
Arguments
Returns
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
Returns
Fields
C
The default C namespace: symbols in the running process.
os
arch
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
s
string
the encoded bytes
Returns
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
v
any
the value to serialize
Returns
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
size
`(integer
table)?`
options
table?
the serialization options
Returns
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
Returns
__concat
__concat : function ( self , other : any ) : string
Arguments
Returns
__tostring
__tostring : function ( self ) : string
Arguments
Returns
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
exclusive b
Buffer
the buffer to append to
...
any
the values to append, in order
Returns
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
exclusive b
Buffer
the buffer to append to
fmt
string
the format string
...
any
the values that the directives consume
Returns
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
exclusive b
Buffer
the buffer to append to
data
voidptr
the memory to copy from
len
integer
how many bytes to copy
Returns
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
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
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
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
tostring
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
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
exclusive b
Buffer
the buffer to empty
Returns
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
exclusive b
Buffer
the buffer to free
Returns
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
exclusive b
Buffer
the buffer to skip in
n
integer
how many bytes to discard
Returns
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
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
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
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
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
exclusive b
Buffer
the buffer that space was reserved in
used
integer
how many bytes were written
Returns
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
exclusive b
Buffer
the buffer to append to
obj
any
the value to serialize
Returns
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
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").
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
func
any
the function to describe
pc
integer?
the bytecode index to resolve currentline from
Returns
{\[string\]: any}
a freshly allocated description table
funcbc
funcbc : function ( func : any , pc : integer ) : ( integer ? , integer ? )
Reads one 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")
funck
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
funcuvname
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
traceinfo
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
traceir
traceir : function ( tr : integer , idx : integer ) : ( integer , integer , integer , integer , integer )
Reads one 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
integer
integer
integer
integer
tracek
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
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
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
tracemc
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
traceexitstub
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
ircalladdr
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
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
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
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
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.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
z
Zone
the zone stack
name
string?
the zone to push, or nil to pop
Returns
string?
the popped zone, when popping
flush
Discards every pushed zone, leaving the stack empty.
Arguments
get
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.
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
The full year, not an offset from 1900.
month
The month, 1 through 12.
day
The day of the month, 1 through 31.
hour
The hour, 0 through 23.
min
The minute, 0 through 59.
sec
The second, 0 through 60, the last of which is a leap second.
wday
The day of the week, 1 for Sunday.
yday
The day of the year, 1 for January 1st.
isdst
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
Returns
flush
flush : function ( self : LuaFile ) : ( boolean ? , string ? )
Arguments
Returns
lines
Arguments
Returns
nosuspend function(): any
read
Arguments
Returns
seek
seek : function ( self : LuaFile , whence : string ? , offset : number ? ) : ( number ? , string ? )
Arguments
self
LuaFile
whence
string?
offset
number?
Returns
setvbuf
setvbuf : function ( self : LuaFile , mode : string , size : number ? ) : ( boolean ? , string ? )
Arguments
self
LuaFile
mode
string
size
number?
Returns
write
Arguments
Returns
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
The declaration's name.
size
Bytes one instance occupies, padding included.
alignment
Required byte alignment of the complete struct.
fingerprint
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
The field's name, as the declaration spells it.
ctype
Its C type, as the generated ffi.typeof spells it.
offset
Bytes from the start of the struct.
size
Bytes the field itself occupies.
alignment
Required byte alignment of the field's C type.
padding
Bytes of alignment padding after it.
← Previous Diagnostics Next → nupp