native_calls_lua/
native_calls_lua.rs1use moonseed::*;
3mod support;
4use support::*;
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 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}
61
62#[cfg(test)]
63#[test]
64fn example_runs_and_asserts_its_result() {
65 main().unwrap();
66}