luaext/
error.rs

1use std::error;
2use std::fmt;
3use std::result;
4use lua;
5
6/// The type of error that occured
7#[derive(Copy, Clone, Debug)]
8pub enum LuaErrorType {
9    RuntimeError,
10    SyntaxError,
11    MemoryError,
12    GcError,
13    MessageHandlerError,
14    FileError,
15}
16
17/// A lua error
18#[derive(Debug)]
19pub struct LuaError {
20    status: LuaErrorType,
21    message: String
22}
23
24impl LuaError {
25    /// Get the type of this error
26    pub fn get_type(&self) -> LuaErrorType {
27        self.status
28    }
29
30    /// Get the error message
31    pub fn get_message(&self) -> &str {
32        &self.message
33    }
34}
35
36impl fmt::Display for LuaError {
37    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
38        write!(f, "{}", self.message)
39    }
40}
41
42impl error::Error for LuaError {
43    fn description(&self) -> &str {
44        &self.message
45    }
46
47    fn cause(&self) -> Option<&error::Error> {
48        None
49    }
50}
51
52/// Result from a Lua call
53pub type Result<T> = result::Result<T, LuaError>;
54
55/// Create a new Okay Lua result from a given value
56pub fn new_luaresult_ok<T>(value: T) -> self::Result<T> {
57    Ok(value)
58}
59
60/// Create a new Lua Error result with a type and an error
61pub fn new_luaresult_err<T>(status: LuaErrorType, message: String) -> self::Result<T> {
62    Err(LuaError{
63        status: status,
64        message: message
65    })
66}
67
68/// uses a ThreadStatus to determine if Lua encountered an error or not
69pub fn get_status_from_threadstatus(status: lua::ThreadStatus)
70        -> result::Result<(), LuaErrorType> {
71    match status {
72        lua::ThreadStatus::Yield => Ok(()),
73        lua::ThreadStatus::Ok    => Ok(()),
74        lua::ThreadStatus::RuntimeError => Err(LuaErrorType::RuntimeError),
75        lua::ThreadStatus::SyntaxError  => Err(LuaErrorType::SyntaxError),
76        lua::ThreadStatus::MemoryError  => Err(LuaErrorType::MemoryError),
77        lua::ThreadStatus::FileError    => Err(LuaErrorType::FileError),
78        lua::ThreadStatus::GcError      => Err(LuaErrorType::GcError),
79        lua::ThreadStatus::MessageHandlerError => Err(LuaErrorType::MessageHandlerError),
80    }
81}
82
83/// Get the error message from a lua state (always the last value on the stack)
84pub fn pop_error_from_state(state: &mut lua::State) -> String {
85    let ret = state.to_str(-1).unwrap().into();
86    state.pop(1);
87    ret
88}