use crate::runtime::Value;
use crate::runtime::table::TableError;
use std::fmt;
#[derive(Clone, Copy, Debug)]
pub struct LuaError(pub Value);
impl LuaError {
pub fn nil() -> LuaError {
LuaError(Value::Nil)
}
pub fn new(v: Value) -> LuaError {
LuaError(v)
}
}
impl fmt::Display for LuaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Value::Str(s) => match std::str::from_utf8(s.as_bytes()) {
Ok(t) => f.write_str(t),
Err(_) => write!(f, "{}", String::from_utf8_lossy(s.as_bytes())),
},
Value::Nil => f.write_str("(nil error)"),
other => write!(f, "(error object is a {} value)", other.type_name()),
}
}
}
impl std::error::Error for LuaError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl From<TableError> for LuaError {
fn from(_: TableError) -> LuaError {
LuaError(Value::Nil)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum LuaErrorKind {
#[default]
Runtime,
Syntax,
InstrBudget,
MemoryCap,
Native,
OutOfMemory,
Type,
}
impl fmt::Display for LuaErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
LuaErrorKind::Runtime => "runtime",
LuaErrorKind::Syntax => "syntax",
LuaErrorKind::InstrBudget => "instr-budget",
LuaErrorKind::MemoryCap => "memory-cap",
LuaErrorKind::Native => "native",
LuaErrorKind::OutOfMemory => "out-of-memory",
LuaErrorKind::Type => "type",
};
f.write_str(s)
}
}