luaext/types/
generic.rs

1use lua::{Index, Type, ToLua, FromLua, State};
2use types::{LuaStackable};
3use context::Context;
4
5/// Represents a generic lua value on the Lua stack
6///
7/// Can represent any possible lua value, and can be converted to a usable value.
8///
9/// # Examples
10///
11/// ```
12/// # use luaext::lua::State;
13/// # use luaext::context::Context;
14/// # use luaext::types::generic::LuaGeneric;
15/// # let mut state = State::new();
16/// # let mut context = Context::new(&mut state);
17/// context.push_integer(4);
18/// let generic: LuaGeneric = context.get_arg(1).unwrap();
19/// assert_eq!(Some(4), generic.get_value(&mut context));
20/// ```
21pub struct LuaGeneric {
22    index: Index
23}
24
25impl LuaGeneric {
26    /// Create a new LuaGeneric given an index
27    pub fn new(i: Index) -> LuaGeneric {
28        LuaGeneric {
29            index: i
30        }
31    }
32
33    /// Gets the Lua type of this generic object
34    pub fn type_of(&self, context: &mut Context) -> Type {
35        context.get_state().type_of(self.index).unwrap()
36    }
37
38    /// Convert the contained value of this generic object to a given type
39    pub fn get_value<T: FromLua>(&self, context: &mut Context) -> Option<T> {
40        context.get_state().to_type(self.index)
41    }
42}
43
44impl LuaStackable for LuaGeneric {
45    fn get_pos(&self) -> Index {
46        self.index
47    }
48}
49
50impl ToLua for LuaGeneric {
51    fn to_lua(&self, state: &mut State) {
52        state.push_value(self.get_pos());
53    }
54}
55
56impl FromLua for LuaGeneric {
57    fn from_lua(_: &mut State, index: Index) -> Option<LuaGeneric> {
58        Some(LuaGeneric::new(index))
59    }
60}