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::<()>(r#"
17        s = Sound.new();
18        s:play();
19
20        print("hello world from within lua!");
21        print("is the sound playing:", s:is_playing());
22
23        s:stop();
24        print("is the sound playing:", s:is_playing());
25
26    "#)
27        .unwrap();
28}
29
30// this `Sound` struct is the object that we will use to demonstrate hlua
31struct Sound {
32    playing: bool,
33}
34
35// this macro implements the required trait so that we can *push* the object to lua
36// (ie. move it inside lua)
37implement_lua_push!(Sound, |mut metatable| {
38    // we create a `__index` entry in the metatable
39    // when the lua code calls `sound:play()`, it will look for `play` in there
40    let mut index = metatable.empty_array("__index");
41
42    index.set("play", hlua::function1(|snd: &mut Sound| snd.play()));
43
44    index.set("stop", hlua::function1(|snd: &mut Sound| snd.stop()));
45
46    index.set("is_playing",
47              hlua::function1(|snd: &Sound| snd.is_playing()));
48});
49
50// this macro implements the require traits so that we can *read* the object back
51implement_lua_read!(Sound);
52
53impl Sound {
54    pub fn new() -> Sound {
55        Sound { playing: false }
56    }
57
58    pub fn play(&mut self) {
59        println!("playing");
60        self.playing = true;
61    }
62
63    pub fn stop(&mut self) {
64        println!("stopping");
65        self.playing = false;
66    }
67
68    pub fn is_playing(&self) -> bool {
69        self.playing
70    }
71}
72
73// this destructor is here to show you that objects are properly getting destroyed
74impl Drop for Sound {
75    fn drop(&mut self) {
76        println!("`Sound` object destroyed");
77    }
78}