bones_scripting/lua/bindings/
resources.rs

1use super::*;
2
3pub fn metatable(ctx: Context) -> Table {
4    let metatable = Table::new(&ctx);
5    let singletons = ctx.singletons();
6    metatable
7        .set(ctx, "__newindex", singletons.get(ctx, no_newindex))
8        .unwrap();
9    metatable
10        .set(
11            ctx,
12            "__tostring",
13            Callback::from_fn(&ctx, |ctx, _fuel, mut stack| {
14                stack.push_front(
15                    piccolo::String::from_static(&ctx, "Resources { len, get }").into(),
16                );
17                Ok(CallbackReturn::Return)
18            }),
19        )
20        .unwrap();
21
22    let get_callback = ctx.registry().stash(
23        &ctx,
24        Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
25            let (world, schema): (&WorldRef, UserData) = stack.consume(ctx)?;
26
27            let schema = schema.downcast_static::<&Schema>()?;
28
29            world.with(|world| {
30                let cell = world.resources.untyped().get_cell(schema);
31                let ecsref = EcsRef {
32                    data: EcsRefData::Resource(cell),
33                    path: default(),
34                }
35                .into_value(ctx);
36                stack.push_front(ecsref);
37            });
38
39            Ok(CallbackReturn::Return)
40        }),
41    );
42
43    metatable
44        .set(
45            ctx,
46            "__index",
47            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
48                let (_world, key): (&WorldRef, lua::String) = stack.consume(ctx)?;
49
50                #[allow(clippy::single_match)]
51                match key.as_bytes() {
52                    b"get" => {
53                        stack.push_front(ctx.registry().fetch(&get_callback).into());
54                    }
55                    _ => (),
56                }
57
58                Ok(CallbackReturn::Return)
59            }),
60        )
61        .unwrap();
62
63    metatable
64}