lua

Bindings for the Lua programming language

lua
moon add tonyfettes/lua@0.1.3
Download zip
Version
0.1.3
License
Apache-2.0
Last updated
8 months ago
Downloads
1K

Dependencies

README

#tonyfettes/lua

MoonBit bindings for the Lua 5.4 programming language.

#Overview

This package provides native bindings to Lua 5.4.8, allowing you to embed and interact with the Lua interpreter from MoonBit code. It includes the complete Lua C API, auxiliary library, and standard libraries.

#Features

  • Full Lua 5.4.8 C API bindings
  • Auxiliary library (aux) for common operations
  • Standard library support (lib) including base, table, and other standard Lua libraries
  • Native execution support (preferred target)
  • Type-safe wrappers for Lua values and state management

#Installation

Add this package to your moon.mod.json:

moon update moon add tonyfettes/lua

#Quick Start

let lua = @aux.new_state()
match lua {
Some(l) => {
// Load standard libraries
@lib.open_libs(l)

// Push and execute Lua code
@lua.push_integer(l, 42)
let value = @lua.to_integer(l, -1)
@lua.pop(l, 1)

// Clean up
@lua.close(l)
}
None => println("Failed to create Lua state")
}

#API Structure

#Core Module (@lua)

The main module provides direct access to the Lua C API:

  • State Management: State type and lifecycle functions
  • Stack Operations: push_*, to_*, pop, etc.
  • Type System: Type enum (Nil, Boolean, Number, String, Table, Function, etc.)
  • Arithmetic & Comparison: arith, compare
  • Loading & Execution: load, pcall, call

#Auxiliary Library (@lua/aux)

Higher-level helper functions:

  • new_state(): Create and initialize a new Lua state
  • Error handling utilities
  • File loading support

#Standard Libraries (@lua/lib)

Access to Lua standard libraries:

  • open_libs(): Load all standard libraries
  • open_base(): Load base library
  • open_table(): Load table library
  • And more...

#Examples

#Basic Arithmetic

test "arith" {
let lua = @aux.new_state()
guard lua is Some(lua) else { fail("cannot create state") }
@lua.push_integer(lua, 10)
@lua.push_integer(lua, 32)
@lua.arith(lua, Add)
let val = @lua.to_integer(lua, -1)
@lua.pop(lua, 1)
@lua.close(lua)
inspect(val, content="42")
}

#Loading and Running Lua Code

test "load" {
let src = b"print(\"Hello, world!\")"
let mut off = 0UL
let lua = @aux.new_state()
guard lua is Some(lua) else { fail("cannot create state") }
defer @lua.close(lua)
@lib.open_libs(lua)

let status = @lua.load(lua, reader_func, "<test>")
guard status is @lua.Ok else { fail("error loading chunk") }

let status = @lua.pcall(lua, 0, 0, 0)
guard status is @lua.Ok else { fail("error calling function") }
}

#Constants

The package exposes important Lua constants:

  • VersionNum: 504
  • Version: "Lua 5.4"
  • Release: "Lua 5.4.8"
  • Status codes: Ok, Yield, ErrRun, ErrSyntax, ErrMem, ErrErr
  • Special indices: registry_index, upvalue_index(i)

#Requirements

  • MoonBit compiler with native target support
  • Dependency: tonyfettes/c (0.6.2)

#Building

This project uses the MoonBit build system:

moon build # Build the project moon test # Run tests moon check # Lint the code

#License

Apache-2.0

#Resources

#Credits

Lua 5.4.8 Copyright (C) 1994-2025 Lua.org, PUC-Rio Authors: R. Ierusalimschy, L. H. de Figueiredo, W. Celes

#
Integer

type Integer = Int64

The type of integers in Lua.

#
Number

type Number = Double

The type of floats in Lua.

#
Alloc

pub(all) type Alloc (
Pointer
[Unit], UInt64, UInt64) ->
Pointer
[Unit]

The type of the memory-allocation function used by Lua states. The allocator function must provide a functionality similar to realloc, but not exactly the same. Its arguments are ptr, a pointer to the block being allocated/reallocated/freed; osize, the original size of the block or some code about what is being allocated; and nsize, the new size of the block.

When ptr is not NULL, osize is the size of the block pointed by ptr, that is, the size given when it was allocated or reallocated.

When ptr is NULL, osize encodes the kind of object that Lua is allocating. osize is any of @lua.TypeString, @lua.TypeTable, @lua.TypeFunction, @lua.TypeUserdata, or @lua.TypeThread when (and only when) Lua is creating a new object of that type. When osize is some other value, Lua is allocating memory for something else.

Lua assumes the following behavior from the allocator function:

When nsize is zero, the allocator must behave like free and then return NULL.

When nsize is not zero, the allocator must behave like realloc. In particular, the allocator returns NULL if and only if it cannot fulfill the request.

Here is a simple implementation for the allocator function. It is used in the auxiliary library by @aux.new_state.

fn l_alloc(
ptr : @c.Pointer[Unit],
osize : UInt64,
nsize : UInt64,
) -> @c.Pointer[Unit] {
ignore(osize)
if nsize == 0 {
@memory.free(ptr)
return @c.Pointer::null()
} else {
return @memory.realloc(ptr, nsize)
}
}

Note that ISO C ensures that free(NULL) has no effect and that realloc(NULL, size) is equivalent to malloc(size).

#
Alloc::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn Alloc::inner(self : Alloc) -> ((
Pointer
[Unit], UInt64, UInt64) ->
Pointer
[Unit])
Convert newtype to its underlying type, automatically derived.

#
ArithOp

pub(all) enum ArithOp {
Add
Sub
Mul
Mod
Pow
Div
IDiv
BAnd
BOr
BXor
Shl
Shr
Unm
BNot
}

#
CFunction

type CFunction

Type for C functions.

In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, @lua.get_top() returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index @lua.get_top(). To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns in C the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results.

As an example, the following function receives a variable number of numeric arguments and returns their average and their sum:

fn foo(l : @lua.State) -> Int {
let n = @lua.get_top(l) // number of arguments
let mut sum = 0.0
for i = 1; i <= n; i = i + 1 {
if !@lua.is_number(l, i) {
@lua.push_string(l, b"incorrect argument")
@lua.error(l)
}
sum @lua.to_number(l, i)
}
@lua.push_number(l, sum / n) // first result
@lua.push_number(l, sum) // second result
return 2 // number of results
}

#
CFunction::invoke

fn CFunction::invoke(self : CFunction, state : State) -> Int

#
CFunction::new

#as_free_fn(c_function)
fn CFunction::new(f : FuncRef[(State) -> Int]) -> CFunction

#
CFunction::to_funcref

fn CFunction::to_funcref(state : CFunction) -> FuncRef[(State) -> Int]

#
CompareOp

pub(all) enum CompareOp {
Eq
Lt
Le
}

#
Debug

pub(all) type Debug
Pointer
[Unit]

A structure used to carry different pieces of information about a function or an activation record. @lua.get_stack fills only the private part of this structure, for later use. To fill the other fields of @lua.Debug with useful information, you must call @lua.get_info with an appropriate parameter. (Specifically, to get a field, you must add the letter between parentheses in the field's comment to the parameter what of @lua.get_info.)

#
Debug::current_line

fn Debug::current_line(ar : Debug) -> Int

The current line where the given function is executing. When no line information is available, current_line returns set to -1.

#
Debug::event

fn Debug::event(ar : Debug) -> Int

#
Debug::f_transfer

fn Debug::f_transfer(ar : Debug) -> Int

The index in the stack of the first value being "transferred", that is, parameters in a call or return values in a return. (The other values are in consecutive indices.) Using this index, you can access and modify these values through @lua.get_local and @lua.set_local. This field is only meaningful during a call hook, denoting the first parameter, or a return hook, denoting the first value being returned. (For call hooks, this value is always 1.)

#
Debug::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn Debug::inner(self : Debug) ->
Pointer
[Unit]
Convert newtype to its underlying type, automatically derived.

#
Debug::is_tail_call

fn Debug::is_tail_call(ar : Debug) -> Bool

True if this function invocation was called by a tail call. In this case, the caller of this level is not in the stack.

#
Debug::is_var_arg

fn Debug::is_var_arg(ar : Debug) -> Bool

True if the function is a variadic function (always true for C functions).

#
Debug::last_line_defined

fn Debug::last_line_defined(ar : Debug) -> Int

The line number where the definition of the function ends.

#
Debug::line_defined

fn Debug::line_defined(ar : Debug) -> Int

The line number where the definition of the function starts.

#
Debug::n_params

fn Debug::n_params(ar : Debug) -> Int

The number of parameters of the function (always 0 for C functions).

#
Debug::n_transfer

fn Debug::n_transfer(ar : Debug) -> Int

The number of values being transferred (see Debug::f_transfer). (For calls of Lua functions, this value is always equal to n_params.)

#
Debug::n_ups

fn Debug::n_ups(ar : Debug) -> Int

The number of upvalues of the function.

#
Debug::name

fn Debug::name(ar : Debug) ->
Pointer
[Byte]

A reasonable name for the given function. Because functions in Lua are first-class values, they do not have a fixed name: some functions can be the value of multiple global variables, while others can be stored only in a table field. The lua_getinfo function checks how the function was called to find a suitable name. If it cannot find a name, then name is set to NULL.

#
Debug::name_what

fn Debug::name_what(ar : Debug) ->
Pointer
[Byte]

Explains the name field. The value of name_what can be "global", "local", "method", "field", "upvalue", or "" (the empty string), according to how the function was called. (Lua uses the empty string when no other option seems to apply.)

#
Debug::short_src

fn Debug::short_src(ar : Debug) ->
Pointer
[Byte]

A "printable" version of source, to be used in error messages.

#
Debug::sizeof

fn Debug::sizeof() -> UInt64

#
Debug::source

fn Debug::source(ar : Debug) ->
Pointer
[Byte]

The source of the chunk that created the function. If source starts with a '@', it means that the function was defined in a file where the file name follows the '@'. If source starts with a '=', the remainder of its contents describes the source in a user-dependent manner. Otherwise, the function was defined in a string where source is that string.

#
Debug::src_len

fn Debug::src_len(ar : Debug) -> UInt64

The length of the string source.

#
Debug::what

fn Debug::what(ar : Debug) ->
Pointer
[Byte]

the string "Lua" if the function is a Lua function, "C" if it is a C function, "main" if it is the main part of a chunk.

#
EventCode

pub(all) enum EventCode {
Call
Ret
Line
Count
TailCall
}

#
GcMode

pub enum GcMode {
Gen
Inc
}

#
Hook

pub(all) type Hook FuncRef[(State, Debug) -> Unit]

Type for debugging hook functions.

Whenever a hook is called, its ar argument has its field event set to the specific event that triggered the hook. Lua identifies these events with the following constants: @lua.HookCall, @lua.HookRet, @lua.HookTailCall, @lua.HookLine, and @lua.HookCount. Moreover, for line events, the field current_line is also set. To get the value of any other field in ar, the hook must call @lua.get_info.

For call events, event can be @lua.HookCall, the normal value, or @lua.HookTailCall, for a tail call; in this case, there will be no corresponding return event.

While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls back Lua to execute a function or a chunk, this execution occurs without any calls to hooks.

Hook functions cannot have continuations, that is, they cannot call @lua.yieldk, @lua.pcallk, or @lua.callk with a non-null k.

Hook functions can yield under the following conditions: Only count and line events can yield; to yield, a hook function must finish its execution calling @lua.yield with nresults equal to zero (that is, with no values).

#
Hook::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn Hook::inner(self : Hook) -> FuncRef[(State, Debug) -> Unit]
Convert newtype to its underlying type, automatically derived.

#
Reader

pub(all) type Reader (State,
Pointer
[UInt64]) ->
Pointer
[Byte]

The reader function used by @lua.load. Every time @lua.load needs another piece of the chunk, it calls the reader, passing along its data parameter. The reader must return a pointer to a block of memory with a new piece of the chunk and set size to the block size. The block must exist until the reader function is called again. To signal the end of the chunk, the reader must return @c.Pointer::null() or set size to zero. The reader function may return pieces of any size greater than zero.

#
Reader::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn Reader::inner(self : Reader) -> ((State,
Pointer
[UInt64]) ->
Pointer
[Byte])
Convert newtype to its underlying type, automatically derived.

#
State

pub(all) type State
Pointer
[Unit]

#
State::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn State::inner(self : State) ->
Pointer
[Unit]
Convert newtype to its underlying type, automatically derived.

#
State::of_pointer

fn State::of_pointer(ptr :
Pointer
[Unit]) -> State

#
State::to_pointer

fn State::to_pointer(self : State) ->
Pointer
[Unit]

#
Type

pub(all) enum Type {
Nil
Boolean
LightUserdata
Number
String
Table
Function
Userdata
Thread
}

impl Eq for Type
impl Show for Type

#
WarnFunction

pub(all) type WarnFunction (Bytes, Bool) -> Unit

The type of warning functions, called by Lua to emit warnings. The first parameter is an opaque pointer set by @lua.set_warn_f. The second parameter is the warning message. The third parameter is a boolean that indicates whether the message is to be continued by the message in the next call.

See warn for more details about warnings.

#
WarnFunction::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn WarnFunction::inner(self : WarnFunction) -> ((Bytes, Bool) -> Unit)
Convert newtype to its underlying type, automatically derived.

#
Writer

pub(all) type Writer (State,
Pointer
[Unit], UInt64) -> Int

The type of the writer function used by @lua.dump. Every time @lua.dump produces another piece of chunk, it calls the writer, passing along the buffer to be written (p) and its size (sz) supplied to @lua.dump.

The writer returns an error code: 0 means no errors; any other value means an error and stops @lua.dump from calling the writer again.

#
Writer::inner

#deprecated("Use `struct T(A)` to declare a newtype and use `.0` access the underlying type instead.")
fn Writer::inner(self : Writer) -> ((State,
Pointer
[Unit], UInt64) -> Int)
Convert newtype to its underlying type, automatically derived.

#
Authors

let Authors : Bytes

let Copyright : Bytes

#
ErrErr

let ErrErr : Int

Error while running the message handler.

#
ErrMem

let ErrMem : Int

Memory allocation error. For such errors, Lua does not call the message handler.

#
ErrRun

let ErrRun : Int

A runtime error.

#
ErrSyntax

let ErrSyntax : Int

Syntax error during precompilation.

#
HookCall

let HookCall : Int

#
HookCount

let HookCount : Int

#
HookLine

let HookLine : Int

#
HookRet

let HookRet : Int

#
HookTailCall

let HookTailCall : Int

#
MaskCall

let MaskCall : Int

#
MaskCount

let MaskCount : Int

#
MaskLine

let MaskLine : Int

#
MaskRet

let MaskRet : Int

#
MinStack

let MinStack : Int

#
MultRet

let MultRet : Int

let Ok : Int

No errors.

#
Release

let Release : Bytes

#
RidxGlobals

let RidxGlobals : Int

#
RidxMainThread

let RidxMainThread : Int

#
Signature

let Signature : Bytes

#
TypeBoolean

let TypeBoolean : Int

#
TypeFunction

let TypeFunction : Int

#
TypeLightUserdata

let TypeLightUserdata : Int

#
TypeNil

let TypeNil : Int

#
TypeNumber

let TypeNumber : Int

#
TypeString

let TypeString : Int

#
TypeTable

let TypeTable : Int

#
TypeThread

let TypeThread : Int

#
TypeUserdata

let TypeUserdata : Int

#
Version

let Version : Bytes

#
VersionMajor

let VersionMajor : Bytes

#
VersionMinor

let VersionMinor : Bytes

#
VersionNum

let VersionNum : Int

#
VersionRelease

let VersionRelease : Bytes

#
VersionReleaseNum

let VersionReleaseNum : Int

#
Yield

let Yield : Int

The thread (coroutine) yields.

#
abs_index

fn abs_index(state : State, index : Int) -> Int

Converts the acceptable index idx into an equivalent absolute index (that is, one that does not depend on the stack size).

#
arith

fn arith(state : State, op : ArithOp) -> Unit

Performs an arithmetic or bitwise operation over the two values (or one, in the case of negations) at the top of the stack, with the value on the top being the second operand, pops these values, and pushes the result of the operation. The function follows the semantics of the corresponding Lua operator (that is, it may call metamethods).

#
at_panic

fn at_panic(state : State, panic_fn : FuncRef[(State) -> Int]) -> CFunction

Sets a new panic function and returns the old one (see §4.4).

#
call

fn call(state : State, nargs : Int, nresults : Int) -> Unit

Calls a function. Like regular Lua calls, @lua.call respects the __call metamethod. So, here the word "function" means any callable value.

To do a call you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the call are pushed in direct order; that is, the first argument is pushed first. Finally you call @lua.call; nargs is the number of arguments that you pushed onto the stack. When the function returns, all arguments and the function value are popped and the call results are pushed onto the stack. The number of results is adjusted to nresults, unless nresults is @lua.MultRet. In this case, all results from the function are pushed; Lua takes care that the returned values fit into the stack space, but it does not ensure any extra space in the stack. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.

Any error while calling and running the function is propagated upwards (with a longjmp).

The following example shows how the host program can do the equivalent to this Lua code:

a = f("how", t.x, 14)

Here it is in MoonBit:

@lua.get_global(lua, "f"); // function to be called
@lua.push_literal(lua, "how"); // 1st argument
@lua.get_global(lua, "t"); // table to be indexed
@lua.get_field(lua, -1, "x"); // push result of t.x (2nd arg)
@lua.remove(lua, -2); // remove 't' from the stack
@lua.push_integer(lua, 14); // 3rd argument
@lua.call(lua, 3, 1); // call 'f' with 3 arguments and 1 result
@lua.set_global(lua, "a"); // set global 'a'

Note that the code above is balanced: at its end, the stack is back to its original configuration. This is considered good programming practice.

#
callk

fn callk(state : State, nargs : Int, nresults : Int, k : (State, Int) -> Int) -> Unit

This function behaves exactly like @lua.call, but allows the called function to yield (see §4.5).

#
check_stack

fn check_stack(state : State, extra : Int) -> Bool

Ensures that the stack has space for at least n extra elements, that is, that you can safely push up to n values into it. It returns false if it cannot fulfill the request, either because it would cause the stack to be greater than a fixed maximum size (typically at least several thousand elements) or because it cannot allocate memory for the extra space. This function never shrinks the stack; if the stack already has space for the extra elements, it is left unchanged.

#
close

fn close(state : State) -> Unit

Close all active to-be-closed variables in the main thread, release all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any), and frees all dynamic memory used by this state.

On several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs that create multiple states, such as daemons or web servers, will probably need to close states as soon as they are not needed.

#
close_slot

fn close_slot(state : State, idx : Int) -> Unit

Close the to-be-closed slot at the given index and set its value to nil The index must be the last index previously marked to be closed (see @lua.to_close) that is still active (that is, not closed yet).

A __close metamethod cannot yield when called through this function.

(This function was introduced in release 5.4.3.)

#
close_thread

fn close_thread(state : State, from? : State) -> Int

Resets a thread, cleaning its call stack and closing all pending to-be-closed variables. Returns a status code: @lua.Ok for no errors in the thread (either the original error that stopped the thread or errors in closing methods), or an error status otherwise. In case of error, leaves the error object on the top of the stack.

The parameter from represents the coroutine that is resetting state. If there is no such coroutine, this parameter can be None.

(This function was introduced in release 5.4.6.)

#
compare

fn compare(state : State, idx1 : Int, idx2 : Int, op : CompareOp) -> Bool

Compares two Lua values. Returns true if the value at index index1 satisfies op when compared with the value at index index2, following the semantics of the corresponding Lua operator (that is, it may call metamethods). Otherwise returns false. Also returns false if any of the indices is not valid.

The value of op must be one of @lua.CompareOp:

  • CompareOp::Eq: compares for equality (==)
  • CompareOp::Lt: compares for less than (<)
  • CompareOp::Le: compares for less than or equal (<=)

#
concat

fn concat(state : State, n : Int) -> Unit

Concatenates the n values at the top of the stack, pops them, and leaves the result on the top. If n is 1, the result is the single value on the stack (that is, the function does nothing); if n is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua (see §3.4.6).

#
copy

fn copy(state : State, from_index : Int, to_index : Int) -> Unit

Copies the element at index from_index into the valid index to_index, replacing the value at that position. Values at other positions are not affected.

#
create_table

fn create_table(state : State, narr : Int, nrec : Int) -> Unit

Creates a new empty table and pushes it onto the stack. Parameter narr is a hint for how many elements the table will have as a sequence; parameter nrec is a hint for how many other elements the table will have. Lua may use these hints to preallocate memory for the new table. This preallocation is useful for performance when you know in advance how many elements the table will have. Otherwise you can use the function @lua.new_table.

#
dump

fn dump(state : State, writer : Writer, strip : Bool) -> Int

Dumps a function as a binary chunk. Receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped. As it produces parts of the chunk, @lua.dump calls function writer (see @lua.Writer) with the given data to write them.

If strip is true, the binary representation may not include all debug information about the function, to save space.

The value returned is the error code returned by the last call to the writer; 0 means no errors.

This function does not pop the Lua function from the stack.

#
error

fn[X] error(state : State) -> X

Raises a Lua error, using the value on the top of the stack as the error object. This function does a long jump, and therefore never returns.

#
gc_collect

fn gc_collect(state : State) -> Unit

Performs a full garbage-collection cycle.

This function should not be called by a finalizer.

#
gc_count

fn gc_count(state : State) -> Int

Returns the current amount of memory (in Kbytes) in use by Lua.

This function should not be called by a finalizer.

#
gc_count_b

fn gc_count_b(state : State) -> Int

Returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.

This function should not be called by a finalizer.

#
gc_gen

fn gc_gen(state : State, minor_mul : Int, major_mul : Int) -> GcMode

Changes the collector to generational mode with the given parameters (see §2.5.2).

Returns the previous mode (GcMode::Gen or GcMode::Inc).

This function should not be called by a finalizer.

#
gc_inc

fn gc_inc(state : State, pause : Int, step_mul : Int, step_size : Int) -> GcMode

Changes the collector to incremental mode with the given parameters (see §2.5.1).

Returns the previous mode (GcMode::Gen or GcMode::Inc).

This function should not be called by a finalizer.

#
gc_is_running

fn gc_is_running(state : State) -> Bool

Returns a boolean that tells whether the collector is running (i.e., not stopped).

This function should not be called by a finalizer.

#
gc_restart

fn gc_restart(state : State) -> Unit

Restarts the garbage collector.

This function should not be called by a finalizer.

#
gc_step

fn gc_step(state : State, step_size : Int) -> Unit

Performs an incremental step of garbage collection, corresponding to the allocation of step_size Kbytes.

This function should not be called by a finalizer.

#
gc_stop

fn gc_stop(state : State) -> Unit

Stops the garbage collector.

This function should not be called by a finalizer.

#
get_alloc_f

fn get_alloc_f(state : State) -> Alloc

Returns the memory-allocation function of a given state.

#
get_field

fn get_field(state : State, index : Int, k : Bytes) -> Type

Pushes onto the stack the value t[k], where t is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4).

Returns the type of the pushed value.

#
get_global

fn get_global(state : State, name : Bytes) -> Type

Pushes onto the stack the value of the global name. Returns the type of that value.

#
get_hook

fn get_hook(state : State) -> Hook

Returns the current hook function.

#
get_hook_count

fn get_hook_count(state : State) -> Int

Returns the current hook count.

#
get_hook_mask

fn get_hook_mask(state : State) -> Int

Returns the current hook mask.

#
get_i

fn get_i(state : State, index : Int, n : Int64) -> Type

Pushes onto the stack the value t[i], where t is the value at the given index. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4).

Returns the type of the pushed value.

#
get_i_user_value

fn get_i_user_value(state : State, idx : Int, n : Int) -> Type?

Pushes onto the stack the n-th user value associated with the full userdata at the given index and returns the type of the pushed value.

If the userdata does not have that value, pushes nil and returns None.

#
get_info

fn get_info(state : State, what : Bytes, ar : Debug) -> Bool

Gets information about a specific function or function invocation.

To get information about a function invocation, the parameter ar must be a valid activation record that was filled by a previous call to @lua.get_stack or given as argument to a hook (see @lua.Hook).

To get information about a function, you push it onto the stack and start the what string with the character '>'. (In that case, @lua.get_info pops the function from the top of the stack.) For instance, to know in which line a function f was defined, you can write the following code:

let ar = Debug(@memory.malloc(Debug::sizeof()));
defer @memory.free(ar.0);
@lua.get_global(lua, "f"); // get global 'f'
@lua.get_info(lua, ">S", ar);
println("\{ar.line_defined()}");

Each character in the string what selects some fields of the structure ar to be filled or a value to be pushed on the stack. (These characters are also documented in the declaration of the structure @lua.Debug, between parentheses in the comments following each field.)

  • 'f': pushes onto the stack the function that is running at the given level;
  • 'l': fills in the field current_line;
  • 'n': fills in the fields name and namewhat;
  • 'r': fills in the fields f_transfer and n_transfer;
  • 'S': fills in the fields source, short_src, line_defined, last_line_defined, and what;
  • 't': fills in the field is_tail_call;
  • 'u': fills in the fields n_ups, n_params, and is_var_arg;
  • 'L': pushes onto the stack a table whose indices are the lines on the function with some associated code, that is, the lines where you can put a break point. (Lines with no code include empty lines and comments.) If this option is given together with option 'f', its table is pushed after the function. This is the only option that can raise a memory error.

This function returns false to signal an invalid option in what; even then the valid options are handled correctly.

#
get_metatable

fn get_metatable(state : State, objindex : Int) -> Bool

If the value at the given index has a metatable, the function pushes that metatable onto the stack and returns true. Otherwise, the function returns false and pushes nothing on the stack.

#
get_stack

fn get_stack(state : State, level : Int, ar : Debug) -> Bool

Gets information about the interpreter runtime stack.

This function fills parts of a @lua.Debug structure with an identification of the activation record of the function executing at a given level. Level 0 is the current running function, whereas level n+1 is the function that has called level n (except for tail calls, which do not count in the stack). When called with a level greater than the stack depth, @lua.get_stack returns false; otherwise it returns true.

#
get_table

fn get_table(state : State, index : Int) -> Type

Pushes onto the stack the value t[k], where t is the value at the given index and k is the value at the top of the stack.

This function pops the key from the stack, pushing the resulting value in its place. As in Lua, this function may trigger a metamethod for the "index" event (see §2.4).

Returns the type of the pushed value.

#
get_top

fn get_top(state : State) -> Int

Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack; in particular, 0 means an empty stack.

#
id_size

let id_size : Int

#
insert

fn insert(state : State, index : Int) -> Unit

Moves the top element into the given valid index, shifting up the elements above this index to open space. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.

#
is_boolean

fn is_boolean(state : State, index : Int) -> Bool

Returns true if the value at the given index is a boolean, and false otherwise.

#
is_c_function

fn is_c_function(state : State, index : Int) -> Bool

Returns true if the value at the given index is a C function, and false otherwise.

#
is_function

fn is_function(state : State, index : Int) -> Bool

Returns true if the value at the given index is a function (either C or Lua), and false otherwise.

#
is_integer

fn is_integer(state : State, index : Int) -> Bool

Returns true if the value at the given index is an integer (that is, the value is a number and is represented as an integer), and false otherwise.

#
is_light_userdata

fn is_light_userdata(state : State, index : Int) -> Bool

Returns true if the value at the given index is a light userdata, and false otherwise.

#
is_nil

fn is_nil(state : State, index : Int) -> Bool

Returns true if the value at the given index is nil, and false otherwise.

#
is_none

fn is_none(state : State, index : Int) -> Bool

Returns true if the given index is not valid, and false otherwise.

#
is_none_or_nil

fn is_none_or_nil(state : State, index : Int) -> Bool

Returns true if the given index is not valid or if the value at this index is nil, and false otherwise.

#
is_number

fn is_number(state : State, index : Int) -> Bool

Returns true if the value at the given index is a number or a string convertible to a number, and false otherwise.

#
is_string

fn is_string(state : State, index : Int) -> Bool

Returns true if the value at the given index is a string or a number (which is always convertible to a string), and false otherwise.

#
is_table

fn is_table(state : State, index : Int) -> Bool

Returns true if the value at the given index is a table, and false otherwise.

#
is_thread

fn is_thread(state : State, index : Int) -> Bool

Returns true if the value at the given index is a thread, and false otherwise.

#
is_userdata

fn is_userdata(state : State, index : Int) -> Bool

Returns true if the value at the given index is a userdata (either full or light), and false otherwise.

#
is_yieldable

fn is_yieldable(state : State) -> Bool

Returns true if the given coroutine can yield, and false otherwise.

#
len

fn len(state : State, index : Int) -> Unit

Returns the length of the value at the given index. It is equivalent to the '#' operator in Lua (see §3.4.7) and may trigger a metamethod for the "length" event (see §2.4). The result is pushed on the stack.

#
load

fn load(state : State, reader : Reader, chunkname : Bytes, mode? : Bytes) -> Int

Loads a Lua chunk without running it. If there are no errors, @lua.load pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message.

The @lua.load function uses a user-supplied reader function to read the chunk (see @lua.Reader). The data argument is an opaque value passed to the reader function.

The chunkname argument gives a name to the chunk, which is used for error messages and in debug information (see §4.7).

@lua.load automatically detects whether the chunk is text or binary and loads it accordingly (see program luac). The string mode works as in function load, with the addition that a None value is equivalent to the string "bt".

@lua.load uses the stack internally, so the reader function must always leave the stack unmodified when returning.

@lua.load can return @lua.Ok, @lua.ErrSyntax, or @lua.ErrMem. The function may also return other values corresponding to errors raised by the read function (see §4.4.1).

If the resulting function has upvalues, its first upvalue is set to the value of the global environment stored at index @lua.RidxGlobals in the registry (see §4.3). When loading main chunks, this upvalue will be the _ENV variable (see §2.2). Other upvalues are initialized with nil.

#
new_state

fn new_state(alloc : Alloc) -> State?

Creates a new independent state and returns its main thread. Returns None if it cannot create the state (due to lack of memory). The argument f is the allocator function; Lua will do all memory allocation for this state through this function (see @lua.Alloc).

#
new_table

fn new_table(state : State) -> Unit

Creates a new empty table and pushes it onto the stack. It is equivalent to @lua.create_table(lua, 0, 0).

#
new_thread

fn new_thread(state : State) -> State?

Creates a new thread, pushes it on the stack, and returns a pointer to a State that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack.

Threads are subject to garbage collection, like any Lua object.

#
new_userdata_uv

fn new_userdata_uv(state : State, size : UInt64, nuvalue : Int) ->
Pointer
[Unit]

This function creates and pushes on the stack a new full userdata, with nuvalue associated Lua values, called user values, plus an associated block of raw memory with size bytes. (The user values can be set and read with the functions @lua.set_i_user_value and @lua.get_i_user_value.)

The function returns the address of the block of memory. Lua ensures that this address is valid as long as the corresponding userdata is alive (see §2.5). Moreover, if the userdata is marked for finalization (see §2.5.3), its address is valid at least until the call to its finalizer.
fn next(state : State, index : Int) -> Bool

Pops a key from the stack, and pushes a key–value pair from the table at the given index, the "next" pair after the given key. If there are no more elements in the table, then lua_next returns 0 and pushes nothing.

A typical table traversal looks like this:

let lua : State = ...
// table is in the stack at index 't'
lua.push_nil()
while lua.next(t) {
// uses 'key' (at index -2) and 'value' (at index -1)
let key_tn = lua.type_name(lua.type_(-2))
let val_tn = lua.type_name(lua.type_(-1))
println("\{key_tn} - \{val_tn}")
// removes 'value'; keeps 'key' for next iteration
lua.pop(1)
}

#
pcall

fn pcall(state : State, nargs : Int, nresults : Int, msgh : Int) -> Int

Calls a function (or a callable object) in protected mode.

Both nargs and nresults have the same meaning as in @lua.call. If there are no errors during the call, @lua.pcall behaves exactly like @lua.call. However, if there is any error, @lua.pcall catches it, pushes a single value on the stack (the error object), and returns an error code. Like @lua.call, @lua.pcall always removes the function and its arguments from the stack.

If msgh is 0, then the error object returned on the stack is exactly the original error object. Otherwise, msgh is the stack index of a message handler. (This index cannot be a pseudo-index.) In case of runtime errors, this handler will be called with the error object and its return value will be the object returned on the stack by @lua.pcall.

Typically, the message handler is used to add more debug information to the error object, such as a stack traceback. Such information cannot be gathered after the return of @lua.pcall, since by then the stack has unwound.

The @lua.pcall function returns one of the following status codes: @lua.Ok, @lua.ErrRun, @lua.ErrMem, or @lua.ErrErr.

#
pcallk

fn pcallk(state : State, nargs : Int, nresults : Int, errfunc : Int, k : (State, Int) -> Int) -> Int

This function behaves exactly like lua_pcall, except that it allows the called function to yield (see §4.5).

#
pop

fn pop(state : State, n : Int) -> Unit

Pops n elements from the stack.

#
push_boolean

fn push_boolean(state : State, b : Bool) -> Unit

Pushes a boolean value with value b onto the stack.

#
push_c_closure

fn push_c_closure(state : State, f : CFunction, n : Int) -> Unit

Pushes a new C closure onto the stack. This function receives a pointer to a C function and pushes onto the stack a Lua value of type function that, when called, invokes the corresponding C function. The parameter n tells how many upvalues this function will have (see §4.2).

Any function to be callable by Lua must follow the correct protocol to receive its parameters and return its results (see @lua.CFunction).

When a C function is created, it is possible to associate some values with it, the so called upvalues; these upvalues are then accessible to the function whenever it is called. This association is called a C closure (see §4.2). To create a C closure, first the initial values for its upvalues must be pushed onto the stack. (When there are multiple upvalues, the first value is pushed first.) Then @lua.push_c_closure is called to create and push the C function onto the stack, with the argument n telling how many values will be associated with the function. @lua.push_c_closure also pops these values from the stack.

The maximum value for n is 255.

When n is zero, this function creates a light C function, which is just a pointer to the C function. In that case, it never raises a memory error.

#
push_c_function

fn push_c_function(state : State, f : CFunction) -> Unit

Pushes a C function onto the stack. This function is equivalent to @lua.push_c_closure with no upvalues.

#
push_integer

fn push_integer(state : State, n : Int64) -> Unit

Pushes an integer with value n onto the stack.

#
push_light_userdata

fn[T] push_light_userdata(state : State, p :
Pointer
[T]) -> Unit

Pushes a light userdata onto the stack.

Userdata represent C values in Lua. A light userdata represents a pointer, a void *. It is a value (like a number): you do not create it, it has no individual metatable, and it is not collected (as it was never created). A light userdata is equal to "any" light userdata with the same C address.

#
push_nil

fn push_nil(state : State) -> Unit

Pushes a nil value onto the stack.

#
push_number

fn push_number(state : State, n : Double) -> Unit

Pushes a float with value n onto the stack.

#
push_string

fn push_string(state : State, s : BytesView) ->
Pointer
[Byte]

Pushes the BytesView pointed to by s onto the stack. Lua will make or reuse an internal copy of the given string, so the memory at s can be freed or reused immediately after the function returns. The BytesView can contain any binary data, including embedded zeros.

Returns a pointer to the internal copy of the string (see §4.1.3).

#
push_thread

fn push_thread(state : State, thread : State) -> Bool

Pushes the thread represented by thread onto the stack. Returns true if this thread is the main thread of its state.

#
push_value

fn push_value(state : State, index : Int) -> Unit

Pushes a copy of the element at the given index onto the stack.

#
raw_equal

fn raw_equal(state : State, idx1 : Int, idx2 : Int) -> Bool

Returns true if the two values in indices index1 and index2 are primitively equal (that is, equal without calling the __eq metamethod). Otherwise returns false. Also returns false if any of the indices are not valid.

#
raw_get

fn raw_get(state : State, index : Int) -> Type

Similar to @lua.get_table, but does a raw access (i.e., without metamethods). The value at index must be a table.

#
raw_get_i

fn raw_get_i(state : State, index : Int, n : Int64) -> Type

Pushes onto the stack the value t[n], where t is the table at the given index. The access is raw, that is, it does not use the __index metavalue.

Returns the type of the pushed value.

#
raw_get_p

fn raw_get_p(state : State, index : Int, p :
Pointer
[Unit]) -> Type

Pushes onto the stack the value t[k], where t is the table at the given index and k is the pointer p represented as a light userdata. The access is raw; that is, it does not use the __index metavalue.

Returns the type of the pushed value.

#
raw_len

fn raw_len(state : State, idx : Int) -> UInt64

Returns the raw "length" of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator ('#') with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata. For other values, this call returns 0.

#
raw_set

fn raw_set(state : State, index : Int) -> Unit

Similar to @lua.set_table, but does a raw assignment (i.e., without metamethods). The value at index must be a table.

#
raw_set_i

fn raw_set_i(state : State, index : Int, n : Int64) -> Unit

Does the equivalent of t[i] = v, where t is the table at the given index and v is the value on the top of the stack.

This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex metavalue.

#
raw_set_p

fn raw_set_p(state : State, index : Int, p :
Pointer
[Unit]) -> Unit

Does the equivalent of t[p] = v, where t is the table at the given index, p is encoded as a light userdata, and v is the value on the top of the stack.

This function pops the value from the stack. The assignment is raw, that is, it does not use the __newindex metavalue.

#
register

fn register(state : State, name : Bytes, f : CFunction) -> Unit

Sets the C function f as the new value of global name.

#
registry_index

let registry_index : Int

#
remove

fn remove(state : State, index : Int) -> Unit

Removes the element at the given valid index, shifting down the elements above this index to fill the gap. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.

#
replace

fn replace(state : State, index : Int) -> Unit

Moves the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pops the top element.

#
reset_thread

#deprecated("Use @lua.close_thread with from being None instead.")
fn reset_thread(state : State, from : State) -> Int

This function is deprecated; it is equivalent to @lua.close_thread with from being None.

#
resume_

fn resume_(state : State, from? : State, nargs : Int, nresults : Ref[Int]) -> Int

Starts and resumes a coroutine in the given thread state.

To start a coroutine, you push the main function plus any arguments onto the empty stack of the thread. then you call @lua.resume_, with nargs being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, *nresults is updated and the top of the stack contains the *nresults values passed to @lua.yield or returned by the body function. @lua.resume_ returns @lua.Yield if the coroutine yields, @lua.Ok if the coroutine finishes its execution without errors, or an error code in case of errors (see §4.4.1). In case of errors, the error object is on the top of the stack.

To resume a coroutine, you remove the *nresults yielded values from its stack, push the values to be passed as results from yield, and then call @lua.resume_.

The parameter from represents the coroutine that is resuming state. If there is no such coroutine, this parameter can be None.

#
rotate

fn rotate(state : State, index : Int, n : Int) -> Unit

Rotates the stack elements between the valid index idx and the top of the stack. The elements are rotated n positions in the direction of the top, for a positive n, or -n positions in the direction of the bottom, for a negative n. The absolute value of n must not be greater than the size of the slice being rotated. This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.

#
set_alloc_f

fn set_alloc_f(state : State, f : Alloc) -> Unit

Changes the allocator function of a given state to f.

#
set_c_stack_limit

fn set_c_stack_limit(state : State, limit : UInt) -> Int

Sets a new limit for the C stack. This limit controls how deeply nested calls can go in Lua, with the intent of avoiding a stack overflow.

Returns the old limit in case of success, or zero in case of error.

#
set_field

fn set_field(state : State, index : Int, k : Bytes) -> Unit

Does the equivalent to t[k] = v, where t is the value at the given index and v is the value on the top of the stack.

This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see §2.4).

#
set_global

fn set_global(state : State, name : Bytes) -> Unit

Pops a value from the stack and sets it as the new value of global name.

#
set_hook

fn set_hook(state : State, func : Hook, mask : Int, count : Int) -> Unit

Sets the debugging hook function.

Argument f is the hook function. mask specifies on which events the hook will be called: it is formed by a bitwise OR of the constants @lua.MaskCall, @lua.MaskRet, @lua.MaskLine, and @lua.MaskCount. The count argument is only meaningful when the mask includes @lua.MaskCount. For each event, the hook is called as explained below:

  • The call hook: is called when the interpreter calls a function. The hook is called just after Lua enters the new function.
  • The return hook: is called when the interpreter returns from a function. The hook is called just before Lua leaves the function.
  • The line hook: is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). This event only happens while Lua is executing a Lua function.
  • The count hook: is called after the interpreter executes every count instructions. This event only happens while Lua is executing a Lua function.

Hooks are disabled by setting mask to zero.

#
set_i

fn set_i(state : State, index : Int, n : Int64) -> Unit

Does the equivalent to t[n] = v, where t is the value at the given index and v is the value on the top of the stack.

This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see §2.4).

#
set_i_user_value

fn set_i_user_value(state : State, idx : Int, n : Int) -> Bool

Pops a value from the stack and sets it as the new n-th user value associated to the full userdata at the given index. Returns false if the userdata does not have that value.

#
set_metatable

fn set_metatable(state : State, objindex : Int) -> Unit

Pops a table or nil from the stack and sets that value as the new metatable for the value at the given index. (nil means no metatable.)

#
set_table

fn set_table(state : State, index : Int) -> Unit

Does the equivalent to t[k] = v, where t is the value at the given index, v is the value on the top of the stack, and k is the value just below the top.

This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event (see §2.4).

#
set_top

fn set_top(state : State, index : Int) -> Unit

Accepts any index, or 0, and sets the stack top to this index. If the new top is greater than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed.

This function can run arbitrary code when removing an index marked as to-be-closed from the stack.

#
set_warn_f

fn set_warn_f(state : State, f : WarnFunction) -> Unit

Sets the warning function to be used by Lua to emit warnings (see @lua.WarnFunction).

#
status

fn status(state : State) -> Int

Returns the status of the thread L.

The status can be @lua.Ok for a normal thread, an error code if the thread finished the execution of a @lua.resume_ with an error, or @lua.Yield if the thread is suspended.

You can call functions only in threads with status @lua.Ok. You can resume threads with status @lua.Ok (to start a new coroutine) or @lua.Yield (to resume a coroutine).

#
string_to_number

fn string_to_number(state : State, s : Bytes) -> UInt64

Converts the zero-terminated string s to a number, pushes that number into the stack, and returns the total size of the string, that is, its length plus one. The conversion can result in an integer or a float, according to the lexical conventions of Lua (see §3.1). The string may have leading and trailing whitespaces and a sign. If the string is not a valid numeral, returns 0 and pushes nothing. (Note that the result can be used as a boolean, true if the conversion succeeds.)

#
to_boolean

fn to_boolean(state : State, index : Int) -> Bool

Converts the Lua value at the given index to a C boolean value (false or true). Like all tests in Lua, @lua.to_boolean returns true for any Lua value different from false and nil; otherwise it returns false. (If you want to accept only actual boolean values, use @lua.is_boolean to test the value's type.)

#
to_c_function

fn to_c_function(state : State, index : Int) -> CFunction?

Converts a value at the given index to a C function. That value must be a C function; otherwise, returns None.

#
to_close

fn to_close(state : State, idx : Int) -> Unit

Marks the given index in the stack as a to-be-closed slot (see §3.3.8). Like a to-be-closed variable in Lua, the value at that slot in the stack will be closed when it goes out of scope. Here, in the context of a C function, to go out of scope means that the running function returns to Lua, or there is an error, or the slot is removed from the stack through lua_settop or lua_pop, or there is a call to lua_closeslot. A slot marked as to-be-closed should not be removed from the stack by any other function in the API except lua_settop or lua_pop, unless previously deactivated by lua_closeslot.

This function raises an error if the value at the given slot neither has a __close metamethod nor is a false value.

This function should not be called for an index that is equal to or below an active to-be-closed slot.

Note that, both in case of errors and of a regular return, by the time the __close metamethod runs, the C stack was already unwound, so that any automatic C variable declared in the calling function (e.g., a buffer) will be out of scope.

#
to_integer

fn to_integer(state : State, index : Int) -> Int64

Equivalent to @lua.to_integer_x with is_num is not used.

#
to_integer_x

fn to_integer_x(state : State, index : Int, is_num : Ref[Bool]) -> Int64

Converts the Lua value at the given index to the signed integral type Integer. The Lua value must be an integer, or a number or string convertible to an integer (see §3.4.3); otherwise, @lua.to_integer_x returns 0.

is_num is assigned a boolean value that indicates whether the operation succeeded.

#
to_number

fn to_number(state : State, index : Int) -> Double

Equivalent to @lua.to_number_x with is_num ignored.

#
to_number_x

fn to_number_x(state : State, idx : Int, is_num : Ref[Bool]) -> Double

Converts the Lua value at the given index to the C type @lua.Number (see @lua.Number). The Lua value must be a number or a string convertible to a number (see §3.4.3); otherwise, @lua.to_number_x returns 0.

is_num is assigned a boolean value that indicates whether the operation succeeded.

#
to_pointer

fn to_pointer(state : State, idx : Int) ->
Pointer
[Unit]

Converts the value at the given index to a generic C pointer (@c.Pointer[Unit]). The value can be a userdata, a table, a thread, a string, or a function; otherwise, lua_topointer returns NULL. Different objects will give different pointers. There is no way to convert the pointer back to its original value.

Typically this function is used only for hashing and debug information.

#
to_string

fn to_string(state : State, index : Int) -> Bytes?

Converts the Lua value at the given index to a C string. The Lua value must be a string or a number; otherwise, the function returns None. If the value is a number, then @lua.to_string also changes the actual value in the stack to a string. (This change confuses next when @lua.to_string is applied to keys during a table traversal.)

@lua.to_string returns a pointer to a string inside the Lua state (see §4.1.3). This string always has a zero ('\0') after its last character (as in C), but can contain other zeros in its body.

This function can raise memory errors only when converting a number to a string (as then it may create a new string).

#
to_thread

fn to_thread(state : State, index : Int) -> State?

Converts the value at the given index to a Lua thread (represented as State). This value must be a thread; otherwise, the function returns None.

#
to_userdata

fn[T] to_userdata(state : State, index : Int) ->
Pointer
[T]

If the value at the given index is a full userdata, returns its memory-block address. If the value is a light userdata, returns its value (a pointer). Otherwise, returns NULL.

#
type_

fn type_(state : State, index : Int) -> Type?

Returns the type of the value in the given valid index, or None for a non-valid but acceptable index. The types returned by @lua.type_ are coded by the following enum variants: Nil, Number, Boolean, String, Table, Function, Userdata, Thread, and LightUserdata.

#
type_name

fn type_name(state : State, type_ : Type?) -> Bytes

Returns the name of the type encoded by the value tp, which must be one the values returned by @lua.type_.

#
upvalue_index

fn upvalue_index(i : Int) -> Int

Returns the pseudo-index that represents the i-th upvalue of the running function (see §4.2). i must be in the range [1,256].

#
version

fn version(state : State) -> Double

Returns the version number of this core.

#
warning

fn warning(state : State, msg : Bytes, to_cont~ : Bool) -> Unit

Emits a warning with the given message. A message in a call with to_cont true should be continued in another call to this function.

See warn for more details about warnings.

#
xmove

fn xmove(from : State, to : State, n : Int) -> Unit

Exchange values between different threads of the same state.

This function pops n values from the stack from, and pushes them onto the stack to.

#
yield_

fn yield_(state : State, nresults : Int) -> Int

This function is equivalent to @lua.yieldk, but it has no continuation (see §4.5). Therefore, when the thread resumes, it continues the function that called the function calling @lua.yield_. To avoid surprises, this function should be called only in a tail call.

#
yieldk

fn yieldk(state : State, nresults : Int, k : (State, Int) -> Int) -> Int

Yields a coroutine (thread).

When a C function calls @lua.yieldk, the running coroutine suspends its execution, and the call to @lua.resume_ that started this coroutine returns. The parameter nresults is the number of values from the stack that will be passed as results to @lua.resume_.

When the coroutine is resumed again, Lua calls the given continuation function k to continue the execution of the C function that yielded (see §4.5). This continuation function receives the same stack from the previous function, with the n results removed and replaced by the arguments passed to @lua.resume_.

Usually, this function does not return; when the coroutine eventually resumes, it continues executing the continuation function. However, there is one special case, which is when this function is called from inside a line or a count hook (see §4.7). In that case, @lua.yieldk should be called with no continuation (probably in the form of @lua.yield) and no results, and the hook should return immediately after the call. Lua will yield and, when the coroutine resumes again, it will continue the normal execution of the (Lua) function that triggered the hook.

This function can raise an error if it is called from a thread with a pending C call with no continuation function (what is called a C-call boundary), or it is called from a thread that is not running inside a resume (typically the main thread).

Source Files