summaryrefslogtreecommitdiff
path: root/tests/scope.rs
blob: 103a9eab5af6a40bc91a1d10ea8e697a6e6038fa (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
extern crate rlua;

use std::cell::Cell;
use std::rc::Rc;

use rlua::{Error, Function, Lua, MetaMethod, String, UserData, UserDataMethods};

#[test]
fn scope_func() {
    let lua = Lua::new();

    let rc = Rc::new(Cell::new(0));
    lua.scope(|scope| {
        let r = rc.clone();
        let f = scope
            .create_function(move |_, ()| {
                r.set(42);
                Ok(())
            })
            .unwrap();
        lua.globals().set("bad", f.clone()).unwrap();
        f.call::<_, ()>(()).unwrap();
        assert_eq!(Rc::strong_count(&rc), 2);
    });
    assert_eq!(rc.get(), 42);
    assert_eq!(Rc::strong_count(&rc), 1);

    match lua
        .globals()
        .get::<_, Function>("bad")
        .unwrap()
        .call::<_, ()>(())
    {
        Err(Error::CallbackError { .. }) => {}
        r => panic!("improper return for destructed function: {:?}", r),
    };
}

#[test]
fn scope_drop() {
    let lua = Lua::new();

    struct MyUserdata(Rc<()>);
    impl UserData for MyUserdata {
        fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
            methods.add_method("method", |_, _, ()| Ok(()));
        }
    }

    let rc = Rc::new(());

    lua.scope(|scope| {
        lua.globals()
            .set(
                "test",
                scope
                    .create_static_userdata(MyUserdata(rc.clone()))
                    .unwrap(),
            )
            .unwrap();
        assert_eq!(Rc::strong_count(&rc), 2);
    });
    assert_eq!(Rc::strong_count(&rc), 1);

    match lua.exec::<()>("test:method()", None) {
        Err(Error::CallbackError { .. }) => {}
        r => panic!("improper return for destructed userdata: {:?}", r),
    };
}

#[test]
fn scope_capture() {
    let lua = Lua::new();

    let mut i = 0;
    lua.scope(|scope| {
        scope
            .create_function_mut(|_, ()| {
                i = 42;
                Ok(())
            })
            .unwrap()
            .call::<_, ()>(())
            .unwrap();
    });
    assert_eq!(i, 42);
}

#[test]
fn outer_lua_access() {
    let lua = Lua::new();
    let table = lua.create_table().unwrap();
    lua.scope(|scope| {
        scope
            .create_function_mut(|_, ()| {
                table.set("a", "b").unwrap();
                Ok(())
            })
            .unwrap()
            .call::<_, ()>(())
            .unwrap();
    });
    assert_eq!(table.get::<_, String>("a").unwrap(), "b");
}

#[test]
fn scope_userdata_methods() {
    struct MyUserData<'a>(&'a Cell<i64>);

    impl<'a> UserData for MyUserData<'a> {
        fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
            methods.add_method("inc", |_, data, ()| {
                data.0.set(data.0.get() + 1);
                Ok(())
            });

            methods.add_method("dec", |_, data, ()| {
                data.0.set(data.0.get() - 1);
                Ok(())
            });
        }
    }

    let lua = Lua::new();

    let i = Cell::new(42);
    lua.scope(|scope| {
        let f: Function =
            lua.eval(
                r#"
                    function(u)
                        u:inc()
                        u:inc()
                        u:inc()
                        u:dec()
                    end
                "#,
                None,
            ).unwrap();

        f.call::<_, ()>(scope.create_nonstatic_userdata(MyUserData(&i)).unwrap())
            .unwrap();
    });

    assert_eq!(i.get(), 44);
}

#[test]
fn scope_userdata_functions() {
    struct MyUserData<'a>(&'a i64);

    impl<'a> UserData for MyUserData<'a> {
        fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
            methods.add_meta_function(MetaMethod::Add, |lua, ()| {
                let globals = lua.globals();
                globals.set("i", globals.get::<_, i64>("i")? + 1)?;
                Ok(())
            });
            methods.add_meta_function(MetaMethod::Sub, |lua, ()| {
                let globals = lua.globals();
                globals.set("i", globals.get::<_, i64>("i")? + 1)?;
                Ok(())
            });
        }
    }

    let lua = Lua::new();
    let f =
        lua.exec::<Function>(
            r#"
                i = 0
                return function(u)
                    _ = u + u
                    _ = u - 1
                    _ = 1 + u
                end
            "#,
            None,
        ).unwrap();

    let dummy = 0;
    lua.scope(|scope| {
        f.call::<_, ()>(scope.create_nonstatic_userdata(MyUserData(&dummy)).unwrap())
            .unwrap();
    });

    assert_eq!(lua.globals().get::<_, i64>("i").unwrap(), 3);
}

#[test]
fn scope_userdata_mismatch() {
    struct MyUserData<'a>(&'a Cell<i64>);

    impl<'a> UserData for MyUserData<'a> {
        fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
            methods.add_method("inc", |_, data, ()| {
                data.0.set(data.0.get() + 1);
                Ok(())
            });
        }
    }

    let lua = Lua::new();
    lua.exec::<()>(
        r#"
            function okay(a, b)
                a.inc(a)
                b.inc(b)
            end

            function bad(a, b)
                a.inc(b)
            end
        "#,
        None,
    ).unwrap();

    let a = Cell::new(1);
    let b = Cell::new(1);

    let okay: Function = lua.globals().get("okay").unwrap();
    let bad: Function = lua.globals().get("bad").unwrap();

    lua.scope(|scope| {
        let au = scope.create_nonstatic_userdata(MyUserData(&a)).unwrap();
        let bu = scope.create_nonstatic_userdata(MyUserData(&b)).unwrap();
        assert!(okay.call::<_, ()>((au.clone(), bu.clone())).is_ok());
        match bad.call::<_, ()>((au, bu)) {
            Err(Error::CallbackError { ref cause, .. }) => match *cause.as_ref() {
                Error::UserDataTypeMismatch => {}
                ref other => panic!("wrong error type {:?}", other),
            },
            Err(other) => panic!("wrong error type {:?}", other),
            Ok(_) => panic!("incorrectly returned Ok"),
        }
    });
}