Skip to main content

Runtime

Struct Runtime 

Source
pub struct Runtime { /* private fields */ }
Expand description

A single-threaded Lua runtime with rooted values and portable checkpoints. It is neither Send nor Sync; drive and complete waits on its owning thread. It owns Lua state, not the host’s HostRegistry callbacks, shared capability backends, or Journal persistence. Owned crate::Value roots keep objects alive; borrowed views cannot cross a mutable execution call.

Construct through Runtime::builder, compile source with crate::compile, and handle every StepOutcome from Runtime::run. Host misuse returns crate::ApiError; uncaught Lua failures are control outcomes, while VM integrity failures return VmError. For native-to-Lua reentry use crate::NativeContext::call_lua. A host callback panic poisons execution and snapshots; discard the runtime after catching it.

Runtime::snapshot captures active VM state, including coroutines and pending calls. Runtime::restore requires an explicit crate::Host, returns a fresh runtime identity, and never restores host callback code or external resources. Drive Runtime::begin_close when Lua cleanup is needed: dropping a runtime executes no Lua.

use moonseed::{compile, FromLuaMulti, Journal, Runtime, StepOutcome};
let mut rt = Runtime::builder().build()?;
rt.load_main(&compile(b"return 42").unwrap())?;
assert_eq!(rt.run(100, &mut Journal::new())?, StepOutcome::Completed);
let values = rt.result_values()?;
assert_eq!(i64::from_lua_multi(values, &mut rt)?, 42);

Implementations§

Source§

impl Runtime

Source

pub fn counter_scope(&self) -> Scope

Scope measurements to this runtime, including host-side API operations. Drop the guard before measuring a different runtime’s host-side work.

Source

pub fn counters(&self) -> Counters

Copy this runtime’s cumulative measurements. Counters are not snapshotted.

Source

pub fn reset_counters(&self)

Start a new measurement interval, also breaking opcode-pair continuity.

Source§

impl Runtime

Source

pub fn capability( &mut self, request: &CapabilityRequest, journal: &mut Journal, ) -> Result<CapabilityPoll, VmError>

Invoke one bounded capability operation through the journal. Both reads and mutations record exact request bytes and final success/failure. Replay mismatches are VM errors and never invoke the capability.

Builtins must retain their work phase on Waiting, return to the executor, and re-enter this helper with the same request after completion. Completion resumes that phase, without delivering Lua results or moving any cursor. This helper requires an active ready thread/frame; it performs no fuel charge. Each read/write request is limited to 64 KiB. Host panics become structured errors. Exactly-once means journal deduplication, not atomic crash durability of an external mutation and the embedder’s journal.

§Errors

Returns VmError::NotRunnable without an active ready call frame, invalid-state errors for unbounded requests, resource errors for oversized request/result storage, journal/replay errors, or VM integrity errors. Host IO failures are retained in the capability result rather than raised here.

Source

pub fn complete_capability( &mut self, key: WaitKey, result: Result<CapabilityValue, HostIoError>, ) -> Result<()>

Complete a capability wait once, retaining the typed final outcome in checkpointed VM state. This does not deliver Lua results: the builtin resumes its work phase and calls capability again, which commits the outcome to its supplied journal without invoking host code. A snapshot taken between completion and that step retains the outcome. Wrong types, oversized results, and duplicate/unknown keys are rejected transactionally.

§Errors

Returns ApiError::NotWaiting or AlreadyCompleted for invalid keys, invalid-state errors for a wrong wait/result type, resource errors for oversized results, or VM integrity errors. A host IO failure is a valid completion value.

Source§

impl Runtime

Source

pub fn install_coroutine(&mut self) -> Result<(), VmError>

Install coroutine (ADR 0041). The registry must have the functions (see crate::register_coroutine).

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn install_debug(&mut self) -> Result<(), VmError>

Install debug (ADR 0040). The registry must have the functions (see crate::register_debug). No standard installer calls this: the library reaches past every boundary a sandbox draws.

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn builder() -> RuntimeBuilder

Begin construction with default configuration and no libraries.

Examples found in repository?
examples/lua_calls_rust.rs (line 12)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.typed(
8        "example.scale",
9        NativePolicy::VmLocal,
10        |_cx, (x, scale): (i64, i64)| Ok(x.wrapping_mul(scale)),
11    );
12    let mut rt = Runtime::builder().registry(registry).build()?;
13    let scale = rt.make_closure("example.scale", ())?;
14    rt.globals().raw_set(&mut rt, "scale", scale)?;
15    assert_eq!(eval::<i64>(&mut rt, b"return scale(6, 7)")?, 42);
16    Ok(())
17}
More examples
Hide additional examples
examples/hello_call.rs (line 13)
5fn main() -> ExampleResult {
6    let events = std::rc::Rc::new(std::cell::Cell::new(0_u64));
7    let count = events.clone();
8    let mut registry = HostRegistry::new();
9    registry.register_hook("example.profiler", move |_| {
10        count.set(count.get() + 1);
11        Ok(HookAction::Continue)
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    rt.set_hook(
15        None,
16        "example.profiler",
17        HookMask::CALL | HookMask::RETURN,
18        0,
19    )?;
20    assert_eq!(eval::<i64>(&mut rt, b"return 6 * 7")?, 42);
21    let add: Function = eval(&mut rt, b"return function(a, b) return a + b, 'ok' end")?;
22    let result: (i64, String) = done(rt.call(&add, (20i64, 22i64), &mut Journal::new(), 100)?)?;
23    assert_eq!(result, (42, "ok".into()));
24    assert!(events.get() > 0);
25    rt.clear_hook(None)?;
26    // The counter is host state; persist it separately if needed on restore.
27    Ok(())
28}
examples/external_rebind.rs (line 35)
32fn main() -> ExampleResult {
33    let mut registry = HostRegistry::new();
34    registry.register_rebind_userdata::<Asset>();
35    let mut rt = Runtime::builder().registry(registry.clone()).build()?;
36    let object = rt.create_host_userdata(
37        Asset {
38            key: b"game/answer".to_vec(),
39            data: Rc::new("old host resource".into()),
40        },
41        0,
42    )?;
43    rt.globals().raw_set(&mut rt, "asset", object)?;
44    let snapshot = rt.snapshot()?;
45    let data: Rc<String> = Rc::new("restored host resource".into());
46    let mut env = HostEnv::new();
47    env.insert(Assets(data.clone()));
48    let mut restored = Runtime::restore(&snapshot, &Host::new(registry).host_env(env))?;
49    let asset: AnyUserData = restored.globals().raw_get(&mut restored, "asset")?;
50    let asset = asset.borrow::<Asset>(&restored)?;
51    assert_eq!(asset.data.as_str(), "restored host resource");
52    assert!(Rc::ptr_eq(&asset.data, &data));
53    Ok(())
54}
examples/tables_and_strings.rs (line 6)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder().build()?;
7    let table = rt.create_table()?;
8    table.raw_set(&mut rt, "answer", 42)?;
9    table.raw_set(&mut rt, "bytes", b"a\0\xff".as_slice())?;
10    let exchange: Function = eval(&mut rt, b"return function(t) return t.answer, t.bytes end")?;
11    let (answer, bytes): (i64, Vec<u8>) =
12        done(rt.call(&exchange, &table, &mut Journal::new(), 100)?)?;
13    assert_eq!(answer, 42);
14    assert_eq!(bytes, b"a\0\xff");
15    assert_eq!(table.raw_get::<_, Vec<u8>>(&mut rt, "bytes")?, bytes);
16    let text = rt.create_string(&bytes)?;
17    assert!(matches!(
18        text.to_str(&rt),
19        Err(Error::Api(ApiError::Conversion(_)))
20    ));
21    table.raw_set(&mut rt, "numeric_text", "42.5")?;
22    assert!(matches!(
23        table.raw_get::<_, f64>(&mut rt, "numeric_text"),
24        Err(Error::Api(ApiError::Conversion(_)))
25    ));
26    let Coerce(number): Coerce<f64> = table.raw_get(&mut rt, "numeric_text")?;
27    assert_eq!(number, 42.5);
28    Ok(())
29}
examples/async_wait.rs (line 13)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
examples/stateful_function.rs (line 23)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.function("example.state", NativePolicy::VmLocal, |cx| {
8        let captures = cx.captures();
9        let Value::UserData(object) = captures[0].to_owned_value()? else {
10            return Err(ApiError::WrongType.into());
11        };
12        let Value::Table(table) = captures[1].to_owned_value()? else {
13            return Err(ApiError::WrongType.into());
14        };
15        let value = {
16            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
17            counter.0 += 1;
18            counter.0
19        };
20        let label: String = cx.raw_get(&table, "label")?;
21        cx.return_values((value, label))
22    });
23    let mut rt = Runtime::builder().registry(registry).build()?;
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let table = rt.create_table()?;
26    table.raw_set(&mut rt, "label", "tick")?;
27    let function = rt.make_closure("example.state", (state, table))?;
28    for n in [41, 42] {
29        let result: (i64, String) = done(rt.call(&function, (), &mut Journal::new(), 100)?)?;
30        assert_eq!(result, (n, "tick".into()));
31    }
32    Ok(())
33}
Source

pub fn new(config: Config, registry: HostRegistry) -> ApiResult<Self>

Construct an idle runtime with this configuration and registry.

§Errors

Returns the construction/resource errors described by RuntimeBuilder::build.

Source

pub fn object(&mut self, id: ObjectId) -> Option<Owned>

Reacquire and root a Lua object by logical identity. Internal prototypes and upvalue cells have no public value representation.

Source

pub fn object_ref(&mut self, id: ObjectId) -> Option<ValueRef<'_>>

Borrow an object without rooting. The borrow prevents collection; an atomic phase is settled before the view is made.

Source

pub fn create_string(&mut self, bytes: impl AsRef<[u8]>) -> ApiResult<LuaString>

Create a rooted byte string, checking the string limit and quota.

§Errors

Returns a resource error when the string, object or logical heap quota is exceeded, or a VM error for invalid internal state.

Examples found in repository?
examples/tables_and_strings.rs (line 16)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder().build()?;
7    let table = rt.create_table()?;
8    table.raw_set(&mut rt, "answer", 42)?;
9    table.raw_set(&mut rt, "bytes", b"a\0\xff".as_slice())?;
10    let exchange: Function = eval(&mut rt, b"return function(t) return t.answer, t.bytes end")?;
11    let (answer, bytes): (i64, Vec<u8>) =
12        done(rt.call(&exchange, &table, &mut Journal::new(), 100)?)?;
13    assert_eq!(answer, 42);
14    assert_eq!(bytes, b"a\0\xff");
15    assert_eq!(table.raw_get::<_, Vec<u8>>(&mut rt, "bytes")?, bytes);
16    let text = rt.create_string(&bytes)?;
17    assert!(matches!(
18        text.to_str(&rt),
19        Err(Error::Api(ApiError::Conversion(_)))
20    ));
21    table.raw_set(&mut rt, "numeric_text", "42.5")?;
22    assert!(matches!(
23        table.raw_get::<_, f64>(&mut rt, "numeric_text"),
24        Err(Error::Api(ApiError::Conversion(_)))
25    ));
26    let Coerce(number): Coerce<f64> = table.raw_get(&mut rt, "numeric_text")?;
27    assert_eq!(number, 42.5);
28    Ok(())
29}
Source

pub fn create_table(&mut self) -> ApiResult<Table>

Create a rooted empty table, checking the quota.

§Errors

Returns a resource error when the object or logical heap quota is exceeded, or a VM error for invalid internal state.

Examples found in repository?
examples/tables_and_strings.rs (line 7)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder().build()?;
7    let table = rt.create_table()?;
8    table.raw_set(&mut rt, "answer", 42)?;
9    table.raw_set(&mut rt, "bytes", b"a\0\xff".as_slice())?;
10    let exchange: Function = eval(&mut rt, b"return function(t) return t.answer, t.bytes end")?;
11    let (answer, bytes): (i64, Vec<u8>) =
12        done(rt.call(&exchange, &table, &mut Journal::new(), 100)?)?;
13    assert_eq!(answer, 42);
14    assert_eq!(bytes, b"a\0\xff");
15    assert_eq!(table.raw_get::<_, Vec<u8>>(&mut rt, "bytes")?, bytes);
16    let text = rt.create_string(&bytes)?;
17    assert!(matches!(
18        text.to_str(&rt),
19        Err(Error::Api(ApiError::Conversion(_)))
20    ));
21    table.raw_set(&mut rt, "numeric_text", "42.5")?;
22    assert!(matches!(
23        table.raw_get::<_, f64>(&mut rt, "numeric_text"),
24        Err(Error::Api(ApiError::Conversion(_)))
25    ));
26    let Coerce(number): Coerce<f64> = table.raw_get(&mut rt, "numeric_text")?;
27    assert_eq!(number, 42.5);
28    Ok(())
29}
More examples
Hide additional examples
examples/stateful_function.rs (line 25)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.function("example.state", NativePolicy::VmLocal, |cx| {
8        let captures = cx.captures();
9        let Value::UserData(object) = captures[0].to_owned_value()? else {
10            return Err(ApiError::WrongType.into());
11        };
12        let Value::Table(table) = captures[1].to_owned_value()? else {
13            return Err(ApiError::WrongType.into());
14        };
15        let value = {
16            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
17            counter.0 += 1;
18            counter.0
19        };
20        let label: String = cx.raw_get(&table, "label")?;
21        cx.return_values((value, label))
22    });
23    let mut rt = Runtime::builder().registry(registry).build()?;
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let table = rt.create_table()?;
26    table.raw_set(&mut rt, "label", "tick")?;
27    let function = rt.make_closure("example.state", (state, table))?;
28    for n in [41, 42] {
29        let result: (i64, String) = done(rt.call(&function, (), &mut Journal::new(), 100)?)?;
30        assert_eq!(result, (n, "tick".into()));
31    }
32    Ok(())
33}
examples/native_calls_lua.rs (line 51)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.bridge", NativePolicy::VmLocal, |cx| {
8        if let Some(resume) = cx.resumed() {
9            assert_eq!(resume.tag, 7);
10            assert!(matches!(resume.kept[0], Value::Integer(1)));
11            match resume.outcome {
12                ResumeOutcome::Returned(values) => Ok(NativeReturn::Return(values)),
13                ResumeOutcome::Errored(error) => Ok(NativeReturn::Error(error.value)),
14            }
15        } else {
16            Ok(NativeReturn::CallLua {
17                function: cx.arg(0).to_owned_value()?,
18                args: MultiValue(vec![Value::Integer(21)]),
19                tag: 7,
20                keep: MultiValue(vec![Value::Integer(1)]),
21            })
22        }
23    });
24    registry.function("example.index", NativePolicy::VmLocal, |cx| {
25        if let Some(resume) = cx.resumed() {
26            return match resume.outcome {
27                ResumeOutcome::Returned(values) => Ok(NativeReturn::Return(values)),
28                ResumeOutcome::Errored(error) => Ok(NativeReturn::Error(error.value)),
29            };
30        }
31        let accessor = cx.captures()[0].to_owned_value()?;
32        let table: Table = cx.argument(0)?;
33        let key = cx.arg(1).to_owned_value()?;
34        // A synchronous Rust read sees no __index-generated field.
35        assert!(matches!(cx.raw_get::<_, Value>(&table, &key)?, Value::Nil));
36        cx.call_lua(accessor, (table, key), 0, ())
37    });
38    let mut rt = Runtime::builder().registry(registry).build()?;
39    let bridge = rt.make_closure("example.bridge", ())?;
40    let lua: Function = eval(&mut rt, b"return function(n) return n * 2 end")?;
41    assert_eq!(
42        done::<i64>(rt.call(&bridge, lua, &mut Journal::new(), 100)?)?,
43        42
44    );
45    let accessor: Function = eval(&mut rt, b"return function(t, key) return t[key] end")?;
46    let index = rt.make_closure("example.index", accessor)?;
47    let handler: Function = eval(
48        &mut rt,
49        b"return function(_, key) if key == 'answer' then return 42 end end",
50    )?;
51    let meta = rt.create_table()?;
52    meta.raw_set(&mut rt, "__index", handler)?;
53    let table = rt.create_table()?;
54    table.set_metatable(&mut rt, Some(&meta))?;
55    assert_eq!(
56        done::<i64>(rt.call(&index, (table, "answer"), &mut Journal::new(), 100)?)?,
57        42
58    );
59    Ok(())
60}
Source

pub fn globals(&mut self) -> Table

Root this runtime’s globals table.

Examples found in repository?
examples/lua_calls_rust.rs (line 14)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.typed(
8        "example.scale",
9        NativePolicy::VmLocal,
10        |_cx, (x, scale): (i64, i64)| Ok(x.wrapping_mul(scale)),
11    );
12    let mut rt = Runtime::builder().registry(registry).build()?;
13    let scale = rt.make_closure("example.scale", ())?;
14    rt.globals().raw_set(&mut rt, "scale", scale)?;
15    assert_eq!(eval::<i64>(&mut rt, b"return scale(6, 7)")?, 42);
16    Ok(())
17}
More examples
Hide additional examples
examples/external_rebind.rs (line 43)
32fn main() -> ExampleResult {
33    let mut registry = HostRegistry::new();
34    registry.register_rebind_userdata::<Asset>();
35    let mut rt = Runtime::builder().registry(registry.clone()).build()?;
36    let object = rt.create_host_userdata(
37        Asset {
38            key: b"game/answer".to_vec(),
39            data: Rc::new("old host resource".into()),
40        },
41        0,
42    )?;
43    rt.globals().raw_set(&mut rt, "asset", object)?;
44    let snapshot = rt.snapshot()?;
45    let data: Rc<String> = Rc::new("restored host resource".into());
46    let mut env = HostEnv::new();
47    env.insert(Assets(data.clone()));
48    let mut restored = Runtime::restore(&snapshot, &Host::new(registry).host_env(env))?;
49    let asset: AnyUserData = restored.globals().raw_get(&mut restored, "asset")?;
50    let asset = asset.borrow::<Asset>(&restored)?;
51    assert_eq!(asset.data.as_str(), "restored host resource");
52    assert!(Rc::ptr_eq(&asset.data, &data));
53    Ok(())
54}
examples/host_userdata.rs (line 28)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.typed(
8        "example.increment",
9        NativePolicy::VmLocal,
10        |cx, (object, n): (AnyUserData, i64)| {
11            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
12            counter.0 += n;
13            Ok(counter.0)
14        },
15    );
16    registry.function("example.counter", NativePolicy::VmLocal, |cx| {
17        let object = cx.create_userdata(Counter(0), 0)?;
18        let methods = cx.create_table()?;
19        let increment = cx.make_closure("example.increment", ())?;
20        cx.raw_set(&methods, "increment", increment)?;
21        let meta = cx.create_table()?;
22        cx.raw_set(&meta, "__index", methods)?;
23        cx.set_metatable(&object, Some(&meta))?;
24        cx.return_values(object)
25    });
26    let mut rt = Runtime::builder().registry(registry).build()?;
27    let constructor = rt.make_closure("example.counter", ())?;
28    rt.globals().raw_set(&mut rt, "counter", constructor)?;
29    assert_eq!(
30        eval::<i64>(
31            &mut rt,
32            b"local c = counter() c:increment(2) return c:increment(40)"
33        )?,
34        42
35    );
36    Ok(())
37}
examples/snapshot_restore.rs (line 26)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
Source

pub fn install_arg( &mut self, script: impl AsRef<[u8]>, args: &[impl AsRef<[u8]>], pre_args: &[impl AsRef<[u8]>], ) -> ApiResult<Table>

Explicitly install Lua’s arg table. pre_args are in command-line order: their last element is arg[-1], and their first is arg[-len]. The script occupies arg[0]; args occupy arg[1..]. Byte strings are preserved. No argument table is installed automatically.

§Errors

Returns conversion/invalid-state errors for unrepresentable indexes, resource errors for string/table allocation, or VM integrity errors.

Source

pub fn load_main(&mut self, chunk: &CompiledChunk) -> ApiResult<()>

Load a chunk onto the idle main thread, preserving globals and its thread identity. Drive it with run. A live chunk is Busy.

§Errors

Returns ApiError::Busy if the main thread is executing a chunk/call; ApiError::InvalidCallState during callbacks, closing, termination or after a poisoned callback; resource errors for allocation; or VM integrity errors.

Examples found in repository?
examples/support/mod.rs (line 30)
29pub fn eval<R: FromLuaMulti>(rt: &mut Runtime, source: &[u8]) -> ExampleResult<R> {
30    rt.load_main(&compile(source)?)?;
31    match rt.run(10_000, &mut Journal::new())? {
32        StepOutcome::Completed => Ok(R::from_lua_multi(rt.result_values()?, rt)?),
33        other => Err(format!("chunk did not complete: {other:?}").into()),
34    }
35}
Source

pub fn result_values(&mut self) -> ApiResult<MultiValue>

Completed main-thread results as rooted values, preserving nil holes.

§Errors

Returns ApiError::InvalidCallState unless the main thread completed, or a VM/root error if its retained results cannot be rooted.

Examples found in repository?
examples/support/mod.rs (line 32)
29pub fn eval<R: FromLuaMulti>(rt: &mut Runtime, source: &[u8]) -> ExampleResult<R> {
30    rt.load_main(&compile(source)?)?;
31    match rt.run(10_000, &mut Journal::new())? {
32        StepOutcome::Completed => Ok(R::from_lua_multi(rt.result_values()?, rt)?),
33        other => Err(format!("chunk did not complete: {other:?}").into()),
34    }
35}
Source

pub fn main_error(&mut self) -> ApiResult<Option<LuaError>>

Read the failed main thread’s unchanged error as a rooted value. Returns None before failure or after replacing the main chunk. Does not consume the failure or turn it into successful results. The error object survives snapshots; live traceback bytes do not.

§Errors

Returns a VM/root error if the failed thread or its error object is invalid. No failure is Ok(None), not an error.

Source§

impl Runtime

Source

pub fn host_env(&self) -> &HostEnv

Resources supplied by the host, never serialized into the runtime.

Source§

impl Runtime

Source

pub fn make_closure( &mut self, symbol: &str, captures: impl IntoLuaMulti, ) -> ApiResult<Function>

Make a registered host native closure. Captures are snapshot state; builtin closure shapes are reserved for the VM.

§Errors

Returns ApiError::UnknownSymbol for absent or reserved symbols, ApiError::InvalidCallState for more than 255 captures, conversion or wrong-runtime errors for captures, and resource/VM errors for allocation.

§Panics

Propagates panics from user-supplied conversion implementations.

Examples found in repository?
examples/lua_calls_rust.rs (line 13)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.typed(
8        "example.scale",
9        NativePolicy::VmLocal,
10        |_cx, (x, scale): (i64, i64)| Ok(x.wrapping_mul(scale)),
11    );
12    let mut rt = Runtime::builder().registry(registry).build()?;
13    let scale = rt.make_closure("example.scale", ())?;
14    rt.globals().raw_set(&mut rt, "scale", scale)?;
15    assert_eq!(eval::<i64>(&mut rt, b"return scale(6, 7)")?, 42);
16    Ok(())
17}
More examples
Hide additional examples
examples/async_wait.rs (line 14)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
examples/stateful_function.rs (line 27)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.function("example.state", NativePolicy::VmLocal, |cx| {
8        let captures = cx.captures();
9        let Value::UserData(object) = captures[0].to_owned_value()? else {
10            return Err(ApiError::WrongType.into());
11        };
12        let Value::Table(table) = captures[1].to_owned_value()? else {
13            return Err(ApiError::WrongType.into());
14        };
15        let value = {
16            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
17            counter.0 += 1;
18            counter.0
19        };
20        let label: String = cx.raw_get(&table, "label")?;
21        cx.return_values((value, label))
22    });
23    let mut rt = Runtime::builder().registry(registry).build()?;
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let table = rt.create_table()?;
26    table.raw_set(&mut rt, "label", "tick")?;
27    let function = rt.make_closure("example.state", (state, table))?;
28    for n in [41, 42] {
29        let result: (i64, String) = done(rt.call(&function, (), &mut Journal::new(), 100)?)?;
30        assert_eq!(result, (n, "tick".into()));
31    }
32    Ok(())
33}
examples/host_userdata.rs (line 27)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.typed(
8        "example.increment",
9        NativePolicy::VmLocal,
10        |cx, (object, n): (AnyUserData, i64)| {
11            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
12            counter.0 += n;
13            Ok(counter.0)
14        },
15    );
16    registry.function("example.counter", NativePolicy::VmLocal, |cx| {
17        let object = cx.create_userdata(Counter(0), 0)?;
18        let methods = cx.create_table()?;
19        let increment = cx.make_closure("example.increment", ())?;
20        cx.raw_set(&methods, "increment", increment)?;
21        let meta = cx.create_table()?;
22        cx.raw_set(&meta, "__index", methods)?;
23        cx.set_metatable(&object, Some(&meta))?;
24        cx.return_values(object)
25    });
26    let mut rt = Runtime::builder().registry(registry).build()?;
27    let constructor = rt.make_closure("example.counter", ())?;
28    rt.globals().raw_set(&mut rt, "counter", constructor)?;
29    assert_eq!(
30        eval::<i64>(
31            &mut rt,
32            b"local c = counter() c:increment(2) return c:increment(40)"
33        )?,
34        42
35    );
36    Ok(())
37}
examples/snapshot_restore.rs (line 25)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
examples/native_calls_lua.rs (line 39)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.bridge", NativePolicy::VmLocal, |cx| {
8        if let Some(resume) = cx.resumed() {
9            assert_eq!(resume.tag, 7);
10            assert!(matches!(resume.kept[0], Value::Integer(1)));
11            match resume.outcome {
12                ResumeOutcome::Returned(values) => Ok(NativeReturn::Return(values)),
13                ResumeOutcome::Errored(error) => Ok(NativeReturn::Error(error.value)),
14            }
15        } else {
16            Ok(NativeReturn::CallLua {
17                function: cx.arg(0).to_owned_value()?,
18                args: MultiValue(vec![Value::Integer(21)]),
19                tag: 7,
20                keep: MultiValue(vec![Value::Integer(1)]),
21            })
22        }
23    });
24    registry.function("example.index", NativePolicy::VmLocal, |cx| {
25        if let Some(resume) = cx.resumed() {
26            return match resume.outcome {
27                ResumeOutcome::Returned(values) => Ok(NativeReturn::Return(values)),
28                ResumeOutcome::Errored(error) => Ok(NativeReturn::Error(error.value)),
29            };
30        }
31        let accessor = cx.captures()[0].to_owned_value()?;
32        let table: Table = cx.argument(0)?;
33        let key = cx.arg(1).to_owned_value()?;
34        // A synchronous Rust read sees no __index-generated field.
35        assert!(matches!(cx.raw_get::<_, Value>(&table, &key)?, Value::Nil));
36        cx.call_lua(accessor, (table, key), 0, ())
37    });
38    let mut rt = Runtime::builder().registry(registry).build()?;
39    let bridge = rt.make_closure("example.bridge", ())?;
40    let lua: Function = eval(&mut rt, b"return function(n) return n * 2 end")?;
41    assert_eq!(
42        done::<i64>(rt.call(&bridge, lua, &mut Journal::new(), 100)?)?,
43        42
44    );
45    let accessor: Function = eval(&mut rt, b"return function(t, key) return t[key] end")?;
46    let index = rt.make_closure("example.index", accessor)?;
47    let handler: Function = eval(
48        &mut rt,
49        b"return function(_, key) if key == 'answer' then return 42 end end",
50    )?;
51    let meta = rt.create_table()?;
52    meta.raw_set(&mut rt, "__index", handler)?;
53    let table = rt.create_table()?;
54    table.set_metatable(&mut rt, Some(&meta))?;
55    assert_eq!(
56        done::<i64>(rt.call(&index, (table, "answer"), &mut Journal::new(), 100)?)?,
57        42
58    );
59    Ok(())
60}
Source

pub fn create_host_userdata<T: HostUserdata>( &mut self, value: T, user_values: usize, ) -> ApiResult<AnyUserData>

Create a rooted full userdata holding a registered Rust payload. With automatic collection on, host allocations collect before refusing for lack of room. Callback borrows defer collection.

§Errors

Returns ApiError::Unregistered if the host type was not registered, or a resource/VM error if the payload and user-value slots cannot be allocated.

§Panics

Propagates a panic from the host payload’s logical_size implementation.

Examples found in repository?
examples/external_rebind.rs (lines 36-42)
32fn main() -> ExampleResult {
33    let mut registry = HostRegistry::new();
34    registry.register_rebind_userdata::<Asset>();
35    let mut rt = Runtime::builder().registry(registry.clone()).build()?;
36    let object = rt.create_host_userdata(
37        Asset {
38            key: b"game/answer".to_vec(),
39            data: Rc::new("old host resource".into()),
40        },
41        0,
42    )?;
43    rt.globals().raw_set(&mut rt, "asset", object)?;
44    let snapshot = rt.snapshot()?;
45    let data: Rc<String> = Rc::new("restored host resource".into());
46    let mut env = HostEnv::new();
47    env.insert(Assets(data.clone()));
48    let mut restored = Runtime::restore(&snapshot, &Host::new(registry).host_env(env))?;
49    let asset: AnyUserData = restored.globals().raw_get(&mut restored, "asset")?;
50    let asset = asset.borrow::<Asset>(&restored)?;
51    assert_eq!(asset.data.as_str(), "restored host resource");
52    assert!(Rc::ptr_eq(&asset.data, &data));
53    Ok(())
54}
More examples
Hide additional examples
examples/stateful_function.rs (line 24)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.function("example.state", NativePolicy::VmLocal, |cx| {
8        let captures = cx.captures();
9        let Value::UserData(object) = captures[0].to_owned_value()? else {
10            return Err(ApiError::WrongType.into());
11        };
12        let Value::Table(table) = captures[1].to_owned_value()? else {
13            return Err(ApiError::WrongType.into());
14        };
15        let value = {
16            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
17            counter.0 += 1;
18            counter.0
19        };
20        let label: String = cx.raw_get(&table, "label")?;
21        cx.return_values((value, label))
22    });
23    let mut rt = Runtime::builder().registry(registry).build()?;
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let table = rt.create_table()?;
26    table.raw_set(&mut rt, "label", "tick")?;
27    let function = rt.make_closure("example.state", (state, table))?;
28    for n in [41, 42] {
29        let result: (i64, String) = done(rt.call(&function, (), &mut Journal::new(), 100)?)?;
30        assert_eq!(result, (n, "tick".into()));
31    }
32    Ok(())
33}
examples/snapshot_restore.rs (line 24)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
Source

pub fn wait(&self, key: WaitKey) -> Option<WaitInfo>

Inspect a pending host operation. Returned object values are rooted in this runtime. Legacy integer waits have no operation payload.

Examples found in repository?
examples/async_wait.rs (line 19)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
Source

pub fn complete( &mut self, key: WaitKey, completion: Completion, ) -> ApiResult<()>

Complete a pending wait once, checking every value’s ownership. Unknown keys are NotWaiting; every completed VM-issued key remains AlreadyCompleted, including after another wait and after restore.

§Errors

Returns ApiError::NotWaiting for unknown keys, AlreadyCompleted for completed keys, InvalidCallState for capability-owned waits, and ownership errors for values from another runtime.

Examples found in repository?
examples/async_wait.rs (line 26)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
Source

pub fn start_call( &mut self, function: &Function, args: impl IntoLuaMulti, ) -> ApiResult<()>

Install a call on the idle main thread. Drive with run, then consume its exact results or Lua error through finish_call.

§Errors

Returns busy/invalid-state errors unless the main thread is idle, wrong-runtime or conversion errors for the function/arguments, and resource/VM errors when preparing the call.

§Panics

Propagates panics from user-supplied conversion implementations.

Source

pub fn finish_call<R: FromLuaMulti>(&mut self) -> ApiResult<R>

Consume a completed host call. A Lua failure retains its original error object; an unfinished call is InvalidCallState.

§Errors

Returns ApiError::InvalidCallState without a finished host call, Error::Lua for an uncaught guest failure, conversion errors for R, or a VM/root error if the retained call state is invalid.

§Panics

Propagates panics from user-supplied conversion implementations.

Examples found in repository?
examples/async_wait.rs (line 28)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
Source

pub fn call<R: FromLuaMulti>( &mut self, function: &Function, args: impl IntoLuaMulti, journal: &mut Journal, fuel: u64, ) -> ApiResult<CallOutcome<R>>

Start and drive a call for at most fuel execution units. This never blocks on a host operation and allocates no Lua thread.

§Errors

Returns the setup errors from Self::start_call, the execution errors from Self::run, or the Lua/conversion errors from Self::finish_call. Termination becomes Error::Vm; a main-thread yield is invalid call state. Fuel pauses and host waits are successful incomplete outcomes, not errors.

§Panics

Propagates panics from host conversions and execution callbacks as described by Self::run.

Examples found in repository?
examples/hello_call.rs (line 22)
5fn main() -> ExampleResult {
6    let events = std::rc::Rc::new(std::cell::Cell::new(0_u64));
7    let count = events.clone();
8    let mut registry = HostRegistry::new();
9    registry.register_hook("example.profiler", move |_| {
10        count.set(count.get() + 1);
11        Ok(HookAction::Continue)
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    rt.set_hook(
15        None,
16        "example.profiler",
17        HookMask::CALL | HookMask::RETURN,
18        0,
19    )?;
20    assert_eq!(eval::<i64>(&mut rt, b"return 6 * 7")?, 42);
21    let add: Function = eval(&mut rt, b"return function(a, b) return a + b, 'ok' end")?;
22    let result: (i64, String) = done(rt.call(&add, (20i64, 22i64), &mut Journal::new(), 100)?)?;
23    assert_eq!(result, (42, "ok".into()));
24    assert!(events.get() > 0);
25    rt.clear_hook(None)?;
26    // The counter is host state; persist it separately if needed on restore.
27    Ok(())
28}
More examples
Hide additional examples
examples/tables_and_strings.rs (line 12)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder().build()?;
7    let table = rt.create_table()?;
8    table.raw_set(&mut rt, "answer", 42)?;
9    table.raw_set(&mut rt, "bytes", b"a\0\xff".as_slice())?;
10    let exchange: Function = eval(&mut rt, b"return function(t) return t.answer, t.bytes end")?;
11    let (answer, bytes): (i64, Vec<u8>) =
12        done(rt.call(&exchange, &table, &mut Journal::new(), 100)?)?;
13    assert_eq!(answer, 42);
14    assert_eq!(bytes, b"a\0\xff");
15    assert_eq!(table.raw_get::<_, Vec<u8>>(&mut rt, "bytes")?, bytes);
16    let text = rt.create_string(&bytes)?;
17    assert!(matches!(
18        text.to_str(&rt),
19        Err(Error::Api(ApiError::Conversion(_)))
20    ));
21    table.raw_set(&mut rt, "numeric_text", "42.5")?;
22    assert!(matches!(
23        table.raw_get::<_, f64>(&mut rt, "numeric_text"),
24        Err(Error::Api(ApiError::Conversion(_)))
25    ));
26    let Coerce(number): Coerce<f64> = table.raw_get(&mut rt, "numeric_text")?;
27    assert_eq!(number, 42.5);
28    Ok(())
29}
examples/async_wait.rs (line 16)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
examples/stateful_function.rs (line 29)
5fn main() -> ExampleResult {
6    let mut registry = counter_registry();
7    registry.function("example.state", NativePolicy::VmLocal, |cx| {
8        let captures = cx.captures();
9        let Value::UserData(object) = captures[0].to_owned_value()? else {
10            return Err(ApiError::WrongType.into());
11        };
12        let Value::Table(table) = captures[1].to_owned_value()? else {
13            return Err(ApiError::WrongType.into());
14        };
15        let value = {
16            let mut counter = cx.borrow_userdata_mut::<Counter>(&object)?;
17            counter.0 += 1;
18            counter.0
19        };
20        let label: String = cx.raw_get(&table, "label")?;
21        cx.return_values((value, label))
22    });
23    let mut rt = Runtime::builder().registry(registry).build()?;
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let table = rt.create_table()?;
26    table.raw_set(&mut rt, "label", "tick")?;
27    let function = rt.make_closure("example.state", (state, table))?;
28    for n in [41, 42] {
29        let result: (i64, String) = done(rt.call(&function, (), &mut Journal::new(), 100)?)?;
30        assert_eq!(result, (n, "tick".into()));
31    }
32    Ok(())
33}
examples/snapshot_restore.rs (line 28)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
examples/native_calls_lua.rs (line 42)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.bridge", NativePolicy::VmLocal, |cx| {
8        if let Some(resume) = cx.resumed() {
9            assert_eq!(resume.tag, 7);
10            assert!(matches!(resume.kept[0], Value::Integer(1)));
11            match resume.outcome {
12                ResumeOutcome::Returned(values) => Ok(NativeReturn::Return(values)),
13                ResumeOutcome::Errored(error) => Ok(NativeReturn::Error(error.value)),
14            }
15        } else {
16            Ok(NativeReturn::CallLua {
17                function: cx.arg(0).to_owned_value()?,
18                args: MultiValue(vec![Value::Integer(21)]),
19                tag: 7,
20                keep: MultiValue(vec![Value::Integer(1)]),
21            })
22        }
23    });
24    registry.function("example.index", NativePolicy::VmLocal, |cx| {
25        if let Some(resume) = cx.resumed() {
26            return match resume.outcome {
27                ResumeOutcome::Returned(values) => Ok(NativeReturn::Return(values)),
28                ResumeOutcome::Errored(error) => Ok(NativeReturn::Error(error.value)),
29            };
30        }
31        let accessor = cx.captures()[0].to_owned_value()?;
32        let table: Table = cx.argument(0)?;
33        let key = cx.arg(1).to_owned_value()?;
34        // A synchronous Rust read sees no __index-generated field.
35        assert!(matches!(cx.raw_get::<_, Value>(&table, &key)?, Value::Nil));
36        cx.call_lua(accessor, (table, key), 0, ())
37    });
38    let mut rt = Runtime::builder().registry(registry).build()?;
39    let bridge = rt.make_closure("example.bridge", ())?;
40    let lua: Function = eval(&mut rt, b"return function(n) return n * 2 end")?;
41    assert_eq!(
42        done::<i64>(rt.call(&bridge, lua, &mut Journal::new(), 100)?)?,
43        42
44    );
45    let accessor: Function = eval(&mut rt, b"return function(t, key) return t[key] end")?;
46    let index = rt.make_closure("example.index", accessor)?;
47    let handler: Function = eval(
48        &mut rt,
49        b"return function(_, key) if key == 'answer' then return 42 end end",
50    )?;
51    let meta = rt.create_table()?;
52    meta.raw_set(&mut rt, "__index", handler)?;
53    let table = rt.create_table()?;
54    table.set_metatable(&mut rt, Some(&meta))?;
55    assert_eq!(
56        done::<i64>(rt.call(&index, (table, "answer"), &mut Journal::new(), 100)?)?,
57        42
58    );
59    Ok(())
60}
Source§

impl Runtime

Source

pub fn begin_close(&mut self) -> Result<(), VmError>

Begin closing the runtime, as lua_close does before it frees the state (ADR 0048): every object registered for finalization joins the queue, after those already in it, newest registration first, and nothing registers from now on. Runtime::run then runs the finalizers, with their errors as warnings, until it returns the run’s own end again; dropping the runtime afterwards frees the rest, and only then do host values’ Rust Drops run. Lua’s __gc semantics at shutdown need this call: dropping a runtime runs no Lua. The run must have ended (completed or failed). Unstable API.

§Errors

Returns VmError::NotRunnable unless the main execution has ended without an active trap, or a VM/resource error while preparing shutdown. Calling again after closing begins succeeds without repeating setup.

Source

pub fn is_closing(&self) -> bool

Whether Runtime::begin_close has run. Unstable API.

Source§

impl Runtime

Source

pub fn set_hook( &mut self, thread: Option<&Value>, symbol: &str, mask: HookMask, count: i32, ) -> Result<()>

Install a registered host hook on the main thread, or a rooted thread. Count is an instruction interval; nonpositive values disable count events.

§Errors

Returns ownership/type errors for an invalid thread, an unknown-symbol error for an unregistered hook when installing one, or VM/resource errors when retained hook state cannot be accessed or allocated.

Examples found in repository?
examples/hello_call.rs (lines 14-19)
5fn main() -> ExampleResult {
6    let events = std::rc::Rc::new(std::cell::Cell::new(0_u64));
7    let count = events.clone();
8    let mut registry = HostRegistry::new();
9    registry.register_hook("example.profiler", move |_| {
10        count.set(count.get() + 1);
11        Ok(HookAction::Continue)
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    rt.set_hook(
15        None,
16        "example.profiler",
17        HookMask::CALL | HookMask::RETURN,
18        0,
19    )?;
20    assert_eq!(eval::<i64>(&mut rt, b"return 6 * 7")?, 42);
21    let add: Function = eval(&mut rt, b"return function(a, b) return a + b, 'ok' end")?;
22    let result: (i64, String) = done(rt.call(&add, (20i64, 22i64), &mut Journal::new(), 100)?)?;
23    assert_eq!(result, (42, "ok".into()));
24    assert!(events.get() > 0);
25    rt.clear_hook(None)?;
26    // The counter is host state; persist it separately if needed on restore.
27    Ok(())
28}
Source

pub fn clear_hook(&mut self, thread: Option<&Value>) -> Result<()>

Clear the main thread’s hook, or a rooted thread’s hook.

§Errors

Returns ownership/type errors for an invalid thread, or a VM/root error when the selected thread or retained hook state is invalid.

Examples found in repository?
examples/hello_call.rs (line 25)
5fn main() -> ExampleResult {
6    let events = std::rc::Rc::new(std::cell::Cell::new(0_u64));
7    let count = events.clone();
8    let mut registry = HostRegistry::new();
9    registry.register_hook("example.profiler", move |_| {
10        count.set(count.get() + 1);
11        Ok(HookAction::Continue)
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    rt.set_hook(
15        None,
16        "example.profiler",
17        HookMask::CALL | HookMask::RETURN,
18        0,
19    )?;
20    assert_eq!(eval::<i64>(&mut rt, b"return 6 * 7")?, 42);
21    let add: Function = eval(&mut rt, b"return function(a, b) return a + b, 'ok' end")?;
22    let result: (i64, String) = done(rt.call(&add, (20i64, 22i64), &mut Journal::new(), 100)?)?;
23    assert_eq!(result, (42, "ok".into()));
24    assert!(events.get() > 0);
25    rt.clear_hook(None)?;
26    // The counter is host state; persist it separately if needed on restore.
27    Ok(())
28}
Source

pub fn get_hook( &mut self, thread: Option<&Value>, ) -> Result<Option<HookSettings>>

Inspect the installed configuration, preserving target identity.

§Errors

Returns ownership/type errors for an invalid thread, or a VM/root error when the selected thread or retained hook state is invalid.

Source§

impl Runtime

Source

pub fn install_io(&mut self) -> Result<(), VmError>

Install Lua IO and its shared file metatable. Installation grants no authority.

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn install_math(&mut self) -> Result<(), VmError>

Install math as a global table: its functions, pi, huge, maxinteger, and mininteger (ADR 0032). The registry must have the functions (see crate::register_math). The generator is seeded from the runtime’s deterministic entropy, never from the clock.

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source

pub fn install_table(&mut self) -> Result<(), VmError>

Install table as a global table of its functions (ADR 0033). The registry must have them (see crate::register_table).

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source

pub fn install_standard(&mut self) -> Result<(), VmError>

Install the base library, package, math, table, string, and coroutine: the standard libraries Moonseed has that a sandbox can keep. debug is left out: it breaks the language’s guarantees (ADR 0040), and a host installs it on purpose. The registry must have them (see crate::register_standard).

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source

pub fn set_entropy(&mut self, entropy: Box<dyn FnMut() -> i64>)

Where math.randomseed() with no argument takes its seeds from (ADR 0032). Host state, not snapshot state. Each seed word is an external effect committed through the journal, so a replay gets the same words. Without one, the seeds come from the runtime’s deterministic entropy stream. Unstable API.

Source§

impl Runtime

Source

pub fn install_os(&mut self) -> Result<(), VmError>

Install the OS table and package.loaded entry without granting authority.

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn install_package(&mut self) -> Result<(), VmError>

Install package and require (ADR 0039): package.loaded and package.preload are the registry’s _LOADED and _PRELOAD, package.searchers holds preload, the optional filesystem Lua searcher, then the optional host resolver. Paths initially default to empty. The registry must have the functions (see crate::register_package).

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn install_string(&mut self) -> Result<(), VmError>

Install string as a global table of its functions, and the string metatable, shared by every string, with __index the string table and Lua 5.4’s arithmetic metamethods (ADR 0034). The registry must have them (see crate::register_string).

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn with_userdata_bytes<R>( &self, id: ObjectId, read: impl FnOnce(&[u8]) -> R, ) -> Option<R>

Lend a byte userdata’s bytes to read. None if id names no byte userdata. Unstable API.

Source

pub fn with_userdata_bytes_mut<R>( &mut self, id: ObjectId, write: impl FnOnce(&mut [u8]) -> R, ) -> Option<R>

Lend a byte userdata’s bytes to write. Their length is fixed. Unstable API.

Source

pub fn with_userdata<T: HostUserdata, R>( &self, id: ObjectId, read: impl FnOnce(&T) -> R, ) -> Option<R>

Lend a host userdata’s value to read, if it is a T. Unstable API.

Source

pub fn with_userdata_mut<T: HostUserdata, R>( &mut self, id: ObjectId, write: impl FnOnce(&mut T) -> R, ) -> Option<R>

Lend a host userdata’s value to write, if it is a T. Its charge then becomes what it declares (logical_size): growth is charged even past the quota, since the host has already made it, and the next allocation sees it; a shrink leaves the logical heap at once. Unstable API.

Source§

impl Runtime

Source

pub fn install_utf8(&mut self) -> Result<(), VmError>

Install the six-field UTF-8 module in globals and package.loaded.

§Errors

Returns a VM resource error when library tables, strings or closures exceed limits, a missing-symbol error if required natives were not registered, or a VM integrity error for invalid runtime state.

Source§

impl Runtime

Source

pub fn fuel_consumed(&self) -> u64

Execution fuel consumed since construction, including snapshot-restored fuel.

Source

pub fn effect_domain(&self) -> u64

The host-selected journal lineage.

Examples found in repository?
examples/snapshot_restore.rs (line 35)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
Source

pub fn next_sequence(&self) -> u64

The next deterministic effect sequence number.

Source

pub fn entry_id(&self) -> Result<ObjectId, VmError>

The main thread’s logical object identity.

Source

pub fn registry(&self) -> &HostRegistry

Borrow the native and userdata registrations used by this runtime.

Source

pub fn contains_id(&self, id: ObjectId) -> bool

Whether this logical object identity is still live.

Source

pub fn root_id(&mut self, id: ObjectId) -> Result<Root, RootError>

Create a legacy explicit root; prefer Runtime::object and owned Value objects.

Source

pub fn release_root(&mut self, root: Root) -> Result<(), RootError>

Release a legacy explicit root in its owning runtime.

Source

pub fn root_alive(&self, root: &Root) -> Result<bool, RootError>

Check whether a legacy explicit root is still registered and live.

Source

pub fn collect(&mut self)

A full collection now (ADR 0050): a cycle still marking is abandoned and one past its atomic phase finishes first, then one whole cycle runs. Like any cycle it resets the debt and sets the next threshold. The host’s own work, so not charged; nothing while a finalizer runs.

Source

pub fn memory(&self) -> MemoryUsage

Read logical heap usage and collection counters.

Source

pub fn set_auto_gc(&mut self, on: bool)

Turn automatic collection on or off. Explicit Runtime::collect works either way. The setting is snapshot state.

Source

pub fn run( &mut self, quantum: u64, journal: &mut Journal, ) -> Result<StepOutcome, VmError>

Drive execution for at most quantum fuel units. API misuse is VmError::Api; Lua failures are StepOutcome::LuaError.

§Errors

Returns VmError::Api for invalid call state or callback API misuse, journal/replay errors when host observations do not match, and VM integrity errors for invalid execution state. Guest failures are StepOutcome::LuaError; fuel/resource termination is a StepOutcome::Terminated, not completion.

§Panics

Propagates panics from host code under the default panic policy. NativePanicPolicy::LuaError catches only its documented callback classes; other host panics still propagate. Discard a runtime poisoned by a panic.

Examples found in repository?
examples/support/mod.rs (line 31)
29pub fn eval<R: FromLuaMulti>(rt: &mut Runtime, source: &[u8]) -> ExampleResult<R> {
30    rt.load_main(&compile(source)?)?;
31    match rt.run(10_000, &mut Journal::new())? {
32        StepOutcome::Completed => Ok(R::from_lua_multi(rt.result_values()?, rt)?),
33        other => Err(format!("chunk did not complete: {other:?}").into()),
34    }
35}
More examples
Hide additional examples
examples/async_wait.rs (line 27)
5fn main() -> ExampleResult {
6    let mut registry = HostRegistry::new();
7    registry.function("example.read", NativePolicy::VmLocal, |cx| {
8        Ok(NativeReturn::Wait(WaitRequest {
9            operation: "read.asset".into(),
10            payload: MultiValue(vec![cx.arg(0).to_owned_value()?]),
11        }))
12    });
13    let mut rt = Runtime::builder().registry(registry).build()?;
14    let read = rt.make_closure("example.read", ())?;
15    let mut journal = Journal::new();
16    let CallOutcome::Waiting(key) = rt.call::<i64>(&read, "answer", &mut journal, 100)? else {
17        return Err("expected a host wait".into());
18    };
19    let request = rt.wait(key).ok_or("missing wait")?;
20    assert_eq!(request.operation, "read.asset");
21    let Value::String(name) = &request.payload[0] else {
22        return Err("expected a string".into());
23    };
24    assert_eq!(name.to_str(&rt)?, "answer");
25    // Submit work here; complete only after the host has its result.
26    rt.complete(key, Completion::Return(vec![Value::Integer(42)]))?;
27    assert_eq!(rt.run(100, &mut journal)?, StepOutcome::Completed);
28    assert_eq!(rt.finish_call::<i64>()?, 42);
29    Ok(())
30}
Source

pub fn run_until_terminal( &mut self, quantum: u64, journal: &mut Journal, ) -> Result<StepOutcome, VmError>

Drive successive quanta until an outcome other than a fuel pause. A zero quantum returns a pause without looping.

§Errors

Returns the errors from Self::run. A wait, yield, Lua error or termination is returned as an outcome; only fuel pauses are retried.

§Panics

Propagates host panics as described by Self::run.

Source

pub fn complete_wait( &mut self, key: WaitKey, result: i64, ) -> Result<(), WaitError>

👎Deprecated:

use Runtime::complete with Completion::Return

End a native wait with one integer result.

Source

pub fn complete_legacy( &mut self, key: WaitKey, completion: LegacyCompletion, ) -> Result<(), WaitError>

👎Deprecated:

use complete with rooted Completion values

End the native call waiting on key: it returns the given values, or raises the given error in the waiting thread, as error(value) would (ADR 0024). A value the heap has no room for raises a memory error instead. CallHost waits take the first value only.

Source

pub fn lua_error(&self) -> Option<(LuaFault, HostValue)>

The error that failed the active thread, or the entry thread: its class and object. The failed thread keeps the object alive; root its id to keep it after the thread goes. Unstable API.

Source

pub fn lua_traceback(&self) -> Option<&[u8]>

Lua-style traceback bytes for the most recent uncaught main-thread error, captured before unwinding. Available after either run or a host call fails, until another main chunk/call is installed. At most 21 frames are formatted; memory failures skip diagnostic allocation. This host diagnostic is not serialized; a restored failed thread keeps its error object but has no traceback. No debug library is required.

Source

pub fn resume_thread( &mut self, id: ObjectId, quantum: u64, journal: &mut Journal, ) -> Result<StepOutcome, VmError>

Resume an existing Lua coroutine and drive it for this quantum. This legacy entry point takes the thread by unrooted logical identity.

§Errors

Returns invalid-call-state errors during/after a failed callback, lookup errors for an invalid thread identity, VmError::NotRunnable unless the coroutine is Lua-suspended, or errors from Self::run_until_terminal.

§Panics

Propagates host panics as described by Self::run.

Source

pub fn call_closure( &mut self, id: ObjectId, journal: &mut Journal, ) -> Result<i64, VmError>

👎Deprecated:

use Runtime::call and Runtime::finish_call with rooted Value objects

Call an unrooted Lua closure through the legacy integer-only path.

Source

pub fn global_integer(&self, key: &str) -> Result<i64, VmError>

👎Deprecated:

use Runtime::call and Runtime::finish_call with rooted Value objects

Read an integer global through the legacy value API.

Source

pub fn results(&self) -> Result<Vec<HostValue>, VmError>

The values the entry function returned, once the run completed, as the host sees them. Unstable API.

Source

pub fn thread_integers(&self, id: ObjectId) -> Result<Vec<i64>, VmError>

👎Deprecated:

use Runtime::call and Runtime::finish_call with rooted Value objects

Read completed coroutine results through the legacy integer-only path.

Source

pub fn limits(&self) -> Limits

The limits this runtime runs under.

Source

pub fn install_base(&mut self) -> Result<(), VmError>

Install Moonseed’s base library: all standard base functions, _G, and _VERSION (ADR 0031). The registry must have them (see crate::register_base). print writes to the output set with Runtime::set_output.

Source

pub fn install_base_only(&mut self, names: &[&str]) -> Result<(), VmError>

Install only the named parts of the base library: names from the standard base functions, _G (the globals table itself), and _VERSION ("Lua 5.4"). A sandbox leaves out what it does not want, such as print or load. Any other name is VmError::UnknownNative. Unstable API.

Source

pub fn set_output(&mut self, output: Box<dyn FnMut(&[u8])>)

Where print writes from now on (ADR 0031). Not snapshot state: set it again on a restored runtime. Unstable API.

Source

pub fn set_warnings(&mut self, warnings: Warnings)

Where warnings go (ADR 0049). Without a sink, warnings are still effects, and go nowhere. Unstable API.

Source

pub fn set_global_native( &mut self, name: &str, symbol: &str, ) -> Result<(), VmError>

Bind global name to the native function registered as symbol. Unstable API.

Source§

impl Runtime

Source

pub fn snapshot(&self) -> Result<Vec<u8>, SnapshotError>

The checkpoint of this runtime, refused with SnapshotError::LimitExceeded past Config::max_snapshot_bytes. Host userdata growth stays charged past the quota (ADR 0044); Userdata charges or collection accounting past it refuse the snapshot (ADR 0052).

§Errors

Returns SnapshotError for callback/poisoned or invalid VM state, nonportable userdata/resources, mismatched userdata registrations, or exceeded snapshot, stack, object or logical heap limits.

§Panics

Propagates panics from host userdata encoders and resource backends.

Examples found in repository?
examples/external_rebind.rs (line 44)
32fn main() -> ExampleResult {
33    let mut registry = HostRegistry::new();
34    registry.register_rebind_userdata::<Asset>();
35    let mut rt = Runtime::builder().registry(registry.clone()).build()?;
36    let object = rt.create_host_userdata(
37        Asset {
38            key: b"game/answer".to_vec(),
39            data: Rc::new("old host resource".into()),
40        },
41        0,
42    )?;
43    rt.globals().raw_set(&mut rt, "asset", object)?;
44    let snapshot = rt.snapshot()?;
45    let data: Rc<String> = Rc::new("restored host resource".into());
46    let mut env = HostEnv::new();
47    env.insert(Assets(data.clone()));
48    let mut restored = Runtime::restore(&snapshot, &Host::new(registry).host_env(env))?;
49    let asset: AnyUserData = restored.globals().raw_get(&mut restored, "asset")?;
50    let asset = asset.borrow::<Asset>(&restored)?;
51    assert_eq!(asset.data.as_str(), "restored host resource");
52    assert!(Rc::ptr_eq(&asset.data, &data));
53    Ok(())
54}
More examples
Hide additional examples
examples/snapshot_restore.rs (line 31)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
Source

pub fn from_snapshot( bytes: &[u8], registry: &HostRegistry, expected_domain: u64, ) -> Result<Self, SnapshotError>

Restore a checkpoint into the default Limits: see Runtime::from_snapshot_with_limits.

§Errors

Returns the decode, policy and resource errors described by Self::from_snapshot_with_limits.

§Panics

Propagates host codec/rebind panics as described by Self::restore.

Source

pub fn from_snapshot_with_limits( bytes: &[u8], registry: &HostRegistry, expected_domain: u64, limits: Limits, ) -> Result<Self, SnapshotError>

Restore a checkpoint into the host’s limits (ADR 0052). The restored runtime runs under, for each limit, the smaller of the snapshot’s and the host’s: equal or larger host limits restore the runtime exactly as it was, and a host limit is never raised. A smaller host limit the state does not fit (more live objects, a longer stack or string, a larger logical heap) refuses the snapshot with SnapshotError::LimitExceeded before any runtime exists. A snapshot longer than limits.max_snapshot_bytes is refused unread, and decoding allocates at most about four times the logical heap it may restore, plus the snapshot’s length.

§Errors

Returns SnapshotError for malformed state, incompatible revisions, a wrong effect domain, missing/denied registrations, failed userdata decoding/rebinding, nonportable resources or exceeded host/snapshot limits.

§Panics

Propagates host codec/rebind panics as described by Self::restore.

Source

pub fn restore(bytes: &[u8], host: &Host) -> Result<Self>

Restore against the host’s registrations, policies, resources, and limits. Validation, codecs, and rebinds finish before a runtime is constructed. Moonseed library symbols allowed by crate::Host::libraries are supplied automatically; the host registry needs only host callbacks, hooks and userdata types. A denied library or absent host symbol returns SnapshotError::UnknownHostSymbol wrapped in crate::Error::Vm. Execution capabilities are optional: print without a sink writes nowhere. Old rooted crate::Value objects belong to the original runtime; reacquire them through globals or Runtime::object after restore. The host retains the journal separately and supplies it to run again; the expected effect domain identifies that journal’s run lineage.

§Errors

Returns Error::Vm(VmError::Snapshot(..)) for malformed data, incompatible revisions, a wrong effect domain, missing/denied registrations, failed userdata codecs/rebinds, nonportable resources or exceeded limits.

§Panics

Propagates panics from host userdata decoders, rebinds and resource backends.

Examples found in repository?
examples/external_rebind.rs (line 48)
32fn main() -> ExampleResult {
33    let mut registry = HostRegistry::new();
34    registry.register_rebind_userdata::<Asset>();
35    let mut rt = Runtime::builder().registry(registry.clone()).build()?;
36    let object = rt.create_host_userdata(
37        Asset {
38            key: b"game/answer".to_vec(),
39            data: Rc::new("old host resource".into()),
40        },
41        0,
42    )?;
43    rt.globals().raw_set(&mut rt, "asset", object)?;
44    let snapshot = rt.snapshot()?;
45    let data: Rc<String> = Rc::new("restored host resource".into());
46    let mut env = HostEnv::new();
47    env.insert(Assets(data.clone()));
48    let mut restored = Runtime::restore(&snapshot, &Host::new(registry).host_env(env))?;
49    let asset: AnyUserData = restored.globals().raw_get(&mut restored, "asset")?;
50    let asset = asset.borrow::<Asset>(&restored)?;
51    assert_eq!(asset.data.as_str(), "restored host resource");
52    assert!(Rc::ptr_eq(&asset.data, &data));
53    Ok(())
54}
More examples
Hide additional examples
examples/snapshot_restore.rs (line 36)
5fn main() -> ExampleResult {
6    let mut rt = Runtime::builder()
7        .registry(counter_registry())
8        .libraries(Libraries::MATH | Libraries::COROUTINE)
9        .build()?;
10    assert_eq!(
11        eval::<i64>(
12            &mut rt,
13            br#"
14        co = coroutine.create(function()
15            local answer = coroutine.yield(20)
16            return answer + 2
17        end)
18        local ok, value = coroutine.resume(co)
19        return value
20    "#
21        )?,
22        20
23    );
24    let state = rt.create_host_userdata(Counter(40), 0)?;
25    let next = rt.make_closure("example.next", state)?;
26    rt.globals().raw_set(&mut rt, "next", &next)?;
27    assert_eq!(
28        done::<i64>(rt.call(&next, (), &mut Journal::new(), 100)?)?,
29        41
30    );
31    let snapshot = rt.snapshot()?;
32    // Fresh host-only registry: Moonseed re-registers its allowed libraries.
33    let host = Host::new(counter_registry())
34        .libraries(Libraries::MATH | Libraries::COROUTINE)
35        .effect_domain(rt.effect_domain());
36    let mut restored = Runtime::restore(&snapshot, &host)?;
37    // The old root belongs to rt. Acquire a new root in restored.
38    let next: Function = restored.globals().raw_get(&mut restored, "next")?;
39    assert_eq!(
40        done::<i64>(restored.call(&next, (), &mut Journal::new(), 100)?)?,
41        42
42    );
43    let (ok, answer, status): (bool, i64, String) = eval(
44        &mut restored,
45        br#"
46        local ok, answer = coroutine.resume(co, math.floor(40.5))
47        return ok, answer, coroutine.status(co)
48    "#,
49    )?;
50    assert!(ok);
51    assert_eq!(answer, 42);
52    assert_eq!(status, "dead");
53    Ok(())
54}
Source§

impl Runtime

Source

pub fn load_chunk( config: Config, registry: HostRegistry, chunk: &CompiledChunk, ) -> Result<Self, VmError>

Instantiate a compiled chunk. Its _ENV is this runtime’s globals table, a fresh empty table. Unstable API.

Source

pub fn load_chunk_with_args( config: Config, registry: HostRegistry, chunk: &CompiledChunk, args: &[HostValue], ) -> Result<Self, VmError>

Self::load_chunk, with args as the chunk’s arguments: ... in the chunk gives them (ADR 0028). A string is made in the new heap; HostValue::Object must name one of its objects. More arguments than the stack bound holds is VmError::StackLimit. Unstable API.

Source

pub fn load_function( &mut self, chunk: &CompiledChunk, ) -> Result<ObjectId, VmError>

A compiled chunk as a function value in this runtime, not yet called, as Lua’s load makes one (ADR 0031): a vararg Lua closure whose _ENV is this runtime’s globals table. Nothing roots it: root it with Runtime::root_id before the next run, or store it where Lua can reach it. Unstable API.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.