1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use super::*;

pub fn metatable(ctx: Context) -> Table {
    let metatable = Table::new(&ctx);
    let singletons = ctx.singletons();
    metatable
        .set(ctx, "__newindex", singletons.get(ctx, no_newindex))
        .unwrap();
    metatable
        .set(
            ctx,
            "__tostring",
            Callback::from_fn(&ctx, |ctx, _fuel, mut stack| {
                stack.push_front(
                    piccolo::String::from_static(&ctx, "Resources { len, get }").into(),
                );
                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();

    let get_callback = ctx.registry().stash(
        &ctx,
        Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
            let (world, schema): (&WorldRef, UserData) = stack.consume(ctx)?;

            let schema = schema.downcast_static::<&Schema>()?;

            world.with(|world| {
                let cell = world.resources.untyped().get_cell(schema);
                let ecsref = EcsRef {
                    data: EcsRefData::Resource(cell),
                    path: default(),
                }
                .into_value(ctx);
                stack.push_front(ecsref);
            });

            Ok(CallbackReturn::Return)
        }),
    );

    metatable
        .set(
            ctx,
            "__index",
            Callback::from_fn(&ctx, move |ctx, _fuel, mut stack| {
                let (_world, key): (&WorldRef, lua::String) = stack.consume(ctx)?;

                #[allow(clippy::single_match)]
                match key.as_bytes() {
                    b"get" => {
                        stack.push_front(ctx.registry().fetch(&get_callback).into());
                    }
                    _ => (),
                }

                Ok(CallbackReturn::Return)
            }),
        )
        .unwrap();

    metatable
}