sound_api/
sound-api.rs

1#[macro_use]
2extern crate hlua;
3
4fn main() {
5    let mut lua = hlua::Lua::new();
6    lua.openlibs();
7
8    // we create a fill an array named `Sound` which will be used as a class-like interface
9    {
10        let mut sound_namespace = lua.empty_array("Sound");
11
12        // creating the `Sound.new` function
13        sound_namespace.set("new", hlua::function0(|| Sound::new()));
14    }
15
16    lua.execute::<()>(
17        r#"
18        s = Sound.new();
19        s:play();
20
21        print("hello world from within lua!");
22        print("is the sound playing:", s:is_playing());
23
24        s:stop();
25        print("is the sound playing:", s:is_playing());
26
27    "#,
28    )
29    .unwrap();
30}
31
32// this `Sound` struct is the object that we will use to demonstrate hlua
33struct Sound {
34    playing: bool,
35}
36
37// this macro implements the required trait so that we can *push* the object to lua
38// (ie. move it inside lua)
39implement_lua_push!(Sound, |mut metatable| {
40    // we create a `__index` entry in the metatable
41    // when the lua code calls `sound:play()`, it will look for `play` in there
42    let mut index = metatable.empty_array("__index");
43
44    index.set("play", hlua::function1(|snd: &mut Sound| snd.play()));
45
46    index.set("stop", hlua::function1(|snd: &mut Sound| snd.stop()));
47
48    index.set(
49        "is_playing",
50        hlua::function1(|snd: &Sound| snd.is_playing()),
51    );
52});
53
54// this macro implements the require traits so that we can *read* the object back
55implement_lua_read!(Sound);
56
57impl Sound {
58    pub fn new() -> Sound {
59        Sound { playing: false }
60    }
61
62    pub fn play(&mut self) {
63        println!("playing");
64        self.playing = true;
65    }
66
67    pub fn stop(&mut self) {
68        println!("stopping");
69        self.playing = false;
70    }
71
72    pub fn is_playing(&self) -> bool {
73        self.playing
74    }
75}
76
77// this destructor is here to show you that objects are properly getting destroyed
78impl Drop for Sound {
79    fn drop(&mut self) {
80        println!("`Sound` object destroyed");
81    }
82}