Skip to main content

stateful_function/
stateful_function.rs

1//! stateful function through the public embedding API.
2use moonseed::*;
3mod support;
4use support::*;
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}
34
35#[cfg(test)]
36#[test]
37fn example_runs_and_asserts_its_result() {
38    main().unwrap();
39}