Remove the `Lua*` prefix from most types

cc #15

Doesn't touch `LuaString` mainly because that's a *lot* of renaming work
and the code looks weird. Also I want feedback before I proceed.
This commit is contained in:
Jonas Schievink 2017-07-18 22:21:12 +02:00
parent 91dbbfe759
commit 9df7727eaa
8 changed files with 508 additions and 505 deletions

View File

@ -6,7 +6,7 @@ use std::f32;
use rlua::*;
fn examples() -> LuaResult<()> {
fn examples() -> Result<()> {
// Create a Lua context with Lua::new(). Eventually, this will allow
// further control on the lua std library, and will specifically allow
// limiting Lua to a subset of "safe" functionality.
@ -56,7 +56,7 @@ fn examples() -> LuaResult<()> {
let v: i64 = map_table.get("two")?;
assert_eq!(v, 2);
// You can pass values like LuaTable back into Lua
// You can pass values like Table back into Lua
globals.set("array_table", array_table)?;
globals.set("map_table", map_table)?;
@ -76,7 +76,7 @@ fn examples() -> LuaResult<()> {
// You can load lua functions
let print: LuaFunction = globals.get("print")?;
let print: Function = globals.get("print")?;
print.call::<_, ()>("hello from rust")?;
// This API handles variadics using Heterogeneous Lists. This is one way to
@ -90,8 +90,8 @@ fn examples() -> LuaResult<()> {
let check_equal = lua.create_function(|lua, args| {
// Functions wrapped in lua receive their arguments packed together as
// LuaMultiValue. The first thing that most wrapped functions will do
// is "unpack" this LuaMultiValue into its parts. Due to lifetime type
// MultiValue. The first thing that most wrapped functions will do
// is "unpack" this MultiValue into its parts. Due to lifetime type
// signature limitations, this cannot be done automatically from the
// function signature, but this will be fixed with ATCs. Notice the use
// of the hlist macros again.
@ -99,7 +99,7 @@ fn examples() -> LuaResult<()> {
// This function just checks whether two string lists are equal, and in
// an inefficient way. Results are returned with lua.pack, which takes
// any number of values and turns them back into LuaMultiValue. In this
// any number of values and turns them back into MultiValue. In this
// way, multiple values can also be returned to Lua. Again, this cannot
// be inferred as part of the function signature due to the same
// lifetime type signature limitations.
@ -110,7 +110,7 @@ fn examples() -> LuaResult<()> {
// You can also accept variadic arguments to rust callbacks.
let join = lua.create_function(|lua, args| {
let strings = lua.unpack::<LuaVariadic<String>>(args)?.0;
let strings = lua.unpack::<Variadic<String>>(args)?.0;
// (This is quadratic!, it's just an example!)
lua.pack(strings.iter().fold("".to_owned(), |a, b| a + b))
});
@ -139,14 +139,14 @@ fn examples() -> LuaResult<()> {
#[derive(Copy, Clone)]
struct Vec2(f32, f32);
impl LuaUserDataType for Vec2 {
fn add_methods(methods: &mut LuaUserDataMethods<Self>) {
impl UserData for Vec2 {
fn add_methods(methods: &mut UserDataMethods<Self>) {
methods.add_method("magnitude", |lua, vec, _| {
let mag_squared = vec.0 * vec.0 + vec.1 * vec.1;
lua.pack(mag_squared.sqrt())
});
methods.add_meta_function(LuaMetaMethod::Add, |lua, params| {
methods.add_meta_function(MetaMethod::Add, |lua, params| {
let hlist_pat![vec1, vec2] = lua.unpack::<HList![Vec2, Vec2]>(params)?;
lua.pack(Vec2(vec1.0 + vec2.0, vec1.1 + vec2.1))
});

View File

@ -20,7 +20,7 @@ fn main() {
loop {
stdin.read_line(&mut line).unwrap();
match lua.eval::<LuaMultiValue>(&line, None) {
match lua.eval::<MultiValue>(&line, None) {
Ok(values) => {
println!(
"{}",
@ -32,7 +32,7 @@ fn main() {
);
break;
}
Err(LuaError::IncompleteStatement(_)) => {
Err(Error::IncompleteStatement(_)) => {
// continue reading input and append it to `line`
write!(stdout, ">> ").unwrap();
stdout.flush().unwrap();

View File

@ -4,126 +4,126 @@ use std::hash::Hash;
use error::*;
use lua::*;
impl<'lua> ToLua<'lua> for LuaValue<'lua> {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
impl<'lua> ToLua<'lua> for Value<'lua> {
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(self)
}
}
impl<'lua> FromLua<'lua> for LuaValue<'lua> {
fn from_lua(lua_value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<Self> {
impl<'lua> FromLua<'lua> for Value<'lua> {
fn from_lua(lua_value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
Ok(lua_value)
}
}
impl<'lua> ToLua<'lua> for LuaString<'lua> {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::String(self))
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::String(self))
}
}
impl<'lua> FromLua<'lua> for LuaString<'lua> {
fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult<LuaString<'lua>> {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<LuaString<'lua>> {
lua.coerce_string(value)
}
}
impl<'lua> ToLua<'lua> for LuaTable<'lua> {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue> {
Ok(LuaValue::Table(self))
impl<'lua> ToLua<'lua> for Table<'lua> {
fn to_lua(self, _: &'lua Lua) -> Result<Value> {
Ok(Value::Table(self))
}
}
impl<'lua> FromLua<'lua> for LuaTable<'lua> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<LuaTable<'lua>> {
impl<'lua> FromLua<'lua> for Table<'lua> {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Table<'lua>> {
match value {
LuaValue::Table(table) => Ok(table),
_ => Err(LuaError::FromLuaConversionError(
Value::Table(table) => Ok(table),
_ => Err(Error::FromLuaConversionError(
"cannot convert lua value to table".to_owned(),
)),
}
}
}
impl<'lua> ToLua<'lua> for LuaFunction<'lua> {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Function(self))
impl<'lua> ToLua<'lua> for Function<'lua> {
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Function(self))
}
}
impl<'lua> FromLua<'lua> for LuaFunction<'lua> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<LuaFunction<'lua>> {
impl<'lua> FromLua<'lua> for Function<'lua> {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Function<'lua>> {
match value {
LuaValue::Function(table) => Ok(table),
_ => Err(LuaError::FromLuaConversionError(
Value::Function(table) => Ok(table),
_ => Err(Error::FromLuaConversionError(
"cannot convert lua value to function".to_owned(),
)),
}
}
}
impl<'lua> ToLua<'lua> for LuaThread<'lua> {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Thread(self))
impl<'lua> ToLua<'lua> for Thread<'lua> {
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Thread(self))
}
}
impl<'lua> FromLua<'lua> for LuaThread<'lua> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<LuaThread<'lua>> {
impl<'lua> FromLua<'lua> for Thread<'lua> {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Thread<'lua>> {
match value {
LuaValue::Thread(t) => Ok(t),
_ => Err(LuaError::FromLuaConversionError(
Value::Thread(t) => Ok(t),
_ => Err(Error::FromLuaConversionError(
"cannot convert lua value to thread".to_owned(),
)),
}
}
}
impl<'lua> ToLua<'lua> for LuaUserData<'lua> {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::UserData(self))
impl<'lua> ToLua<'lua> for AnyUserData<'lua> {
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::UserData(self))
}
}
impl<'lua> FromLua<'lua> for LuaUserData<'lua> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<LuaUserData<'lua>> {
impl<'lua> FromLua<'lua> for AnyUserData<'lua> {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<AnyUserData<'lua>> {
match value {
LuaValue::UserData(ud) => Ok(ud),
_ => Err(LuaError::FromLuaConversionError(
Value::UserData(ud) => Ok(ud),
_ => Err(Error::FromLuaConversionError(
"cannot convert lua value to userdata".to_owned(),
)),
}
}
}
impl<'lua, T: LuaUserDataType> ToLua<'lua> for T {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::UserData(lua.create_userdata(self)))
impl<'lua, T: UserData> ToLua<'lua> for T {
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::UserData(lua.create_userdata(self)))
}
}
impl<'lua, T: LuaUserDataType + Copy> FromLua<'lua> for T {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<T> {
impl<'lua, T: UserData + Copy> FromLua<'lua> for T {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<T> {
match value {
LuaValue::UserData(ud) => Ok(*ud.borrow::<T>()?),
_ => Err(LuaError::FromLuaConversionError(
Value::UserData(ud) => Ok(*ud.borrow::<T>()?),
_ => Err(Error::FromLuaConversionError(
"cannot convert lua value to userdata".to_owned(),
)),
}
}
}
impl<'lua> ToLua<'lua> for LuaError {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Error(self))
impl<'lua> ToLua<'lua> for Error {
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Error(self))
}
}
impl<'lua> FromLua<'lua> for LuaError {
fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult<LuaError> {
impl<'lua> FromLua<'lua> for Error {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Error> {
match value {
LuaValue::Error(err) => Ok(err),
val => Ok(LuaError::RuntimeError(
Value::Error(err) => Ok(err),
val => Ok(Error::RuntimeError(
lua.coerce_string(val)
.and_then(|s| Ok(s.to_str()?.to_owned()))
.unwrap_or_else(|_| "<unprintable error>".to_owned()),
@ -133,32 +133,32 @@ impl<'lua> FromLua<'lua> for LuaError {
}
impl<'lua> ToLua<'lua> for bool {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Boolean(self))
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Boolean(self))
}
}
impl<'lua> FromLua<'lua> for bool {
fn from_lua(v: LuaValue, _: &'lua Lua) -> LuaResult<Self> {
fn from_lua(v: Value, _: &'lua Lua) -> Result<Self> {
match v {
LuaValue::Nil => Ok(false),
LuaValue::Boolean(b) => Ok(b),
Value::Nil => Ok(false),
Value::Boolean(b) => Ok(b),
_ => Ok(true),
}
}
}
impl<'lua> ToLua<'lua> for LuaLightUserData {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::LightUserData(self))
impl<'lua> ToLua<'lua> for LightUserData {
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::LightUserData(self))
}
}
impl<'lua> FromLua<'lua> for LuaLightUserData {
fn from_lua(v: LuaValue, _: &'lua Lua) -> LuaResult<Self> {
impl<'lua> FromLua<'lua> for LightUserData {
fn from_lua(v: Value, _: &'lua Lua) -> Result<Self> {
match v {
LuaValue::LightUserData(ud) => Ok(ud),
_ => Err(LuaError::FromLuaConversionError(
Value::LightUserData(ud) => Ok(ud),
_ => Err(Error::FromLuaConversionError(
"cannot convert lua value to lightuserdata".to_owned(),
)),
}
@ -166,33 +166,33 @@ impl<'lua> FromLua<'lua> for LuaLightUserData {
}
impl<'lua> ToLua<'lua> for String {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::String(lua.create_string(&self)))
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::String(lua.create_string(&self)))
}
}
impl<'lua> FromLua<'lua> for String {
fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Self> {
Ok(lua.coerce_string(value)?.to_str()?.to_owned())
}
}
impl<'lua, 'a> ToLua<'lua> for &'a str {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::String(lua.create_string(self)))
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::String(lua.create_string(self)))
}
}
macro_rules! lua_convert_int {
($x: ty) => {
impl<'lua> ToLua<'lua> for $x {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Integer(self as LuaInteger))
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Integer(self as Integer))
}
}
impl<'lua> FromLua<'lua> for $x {
fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Self> {
Ok(lua.coerce_integer(value)? as $x)
}
}
@ -213,13 +213,13 @@ lua_convert_int!(usize);
macro_rules! lua_convert_float {
($x: ty) => {
impl<'lua> ToLua<'lua> for $x {
fn to_lua(self, _: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Number(self as LuaNumber))
fn to_lua(self, _: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Number(self as Number))
}
}
impl<'lua> FromLua<'lua> for $x {
fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Self> {
Ok(lua.coerce_number(value)? as $x)
}
}
@ -230,17 +230,17 @@ lua_convert_float!(f32);
lua_convert_float!(f64);
impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Vec<T> {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Table(lua.create_sequence_from(self)?))
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Table(lua.create_sequence_from(self)?))
}
}
impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Vec<T> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<Self> {
if let LuaValue::Table(table) = value {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
if let Value::Table(table) = value {
table.sequence_values().collect()
} else {
Err(LuaError::FromLuaConversionError(
Err(Error::FromLuaConversionError(
"cannot convert lua value to table for Vec".to_owned(),
))
}
@ -248,17 +248,17 @@ impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Vec<T> {
}
impl<'lua, K: Eq + Hash + ToLua<'lua>, V: ToLua<'lua>> ToLua<'lua> for HashMap<K, V> {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Table(lua.create_table_from(self)?))
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Table(lua.create_table_from(self)?))
}
}
impl<'lua, K: Eq + Hash + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for HashMap<K, V> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<Self> {
if let LuaValue::Table(table) = value {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
if let Value::Table(table) = value {
table.pairs().collect()
} else {
Err(LuaError::FromLuaConversionError(
Err(Error::FromLuaConversionError(
"cannot convert lua value to table for HashMap".to_owned(),
))
}
@ -266,17 +266,17 @@ impl<'lua, K: Eq + Hash + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for Has
}
impl<'lua, K: Ord + ToLua<'lua>, V: ToLua<'lua>> ToLua<'lua> for BTreeMap<K, V> {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
Ok(LuaValue::Table(lua.create_table_from(self)?))
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
Ok(Value::Table(lua.create_table_from(self)?))
}
}
impl<'lua, K: Ord + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for BTreeMap<K, V> {
fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult<Self> {
if let LuaValue::Table(table) = value {
fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Self> {
if let Value::Table(table) = value {
table.pairs().collect()
} else {
Err(LuaError::FromLuaConversionError(
Err(Error::FromLuaConversionError(
"cannot convert lua value to table for BTreeMap".to_owned(),
))
}
@ -284,7 +284,7 @@ impl<'lua, K: Ord + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for BTreeMap<
}
impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option<T> {
fn to_lua(self, lua: &'lua Lua) -> LuaResult<LuaValue<'lua>> {
fn to_lua(self, lua: &'lua Lua) -> Result<Value<'lua>> {
match self {
Some(val) => val.to_lua(lua),
None => Ok(LuaNil),
@ -293,7 +293,7 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option<T> {
}
impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option<T> {
fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result<Self> {
match value {
LuaNil => Ok(None),
value => Ok(Some(T::from_lua(value, lua)?)),

View File

@ -1,10 +1,9 @@
use std::fmt;
use std::sync::Arc;
use std::result::Result;
use std::error::Error;
use std::error;
#[derive(Debug, Clone)]
pub enum LuaError {
pub enum Error {
/// Lua syntax error, aka `LUA_ERRSYNTAX` that is NOT an incomplete statement.
SyntaxError(String),
/// Lua syntax error that IS an incomplete statement. Useful for implementing a REPL.
@ -17,7 +16,7 @@ pub enum LuaError {
ToLuaConversionError(String),
/// A generic Lua -> Rust conversion error.
FromLuaConversionError(String),
/// A `LuaThread` was resumed and the coroutine was no longer active.
/// A `Thread` was resumed and the coroutine was no longer active.
CoroutineInactive,
/// A `LuaUserData` is not the expected type in a borrow.
UserDataTypeMismatch,
@ -25,87 +24,87 @@ pub enum LuaError {
UserDataBorrowError,
/// A `LuaUserData` mutable borrow failed because it is already borrowed.
UserDataBorrowMutError,
/// Lua error that originated as a LuaError in a callback. The first field is the lua error as
/// a string, the second field is the Arc holding the original LuaError.
CallbackError(String, Arc<LuaError>),
/// Lua error that originated as a Error in a callback. The first field is the lua error as
/// a string, the second field is the Arc holding the original Error.
CallbackError(String, Arc<Error>),
/// Any custom external error type, mostly useful for returning external error types from
/// callbacks.
ExternalError(Arc<Error + Send + Sync>),
ExternalError(Arc<error::Error + Send + Sync>),
}
pub type LuaResult<T> = Result<T, LuaError>;
pub type Result<T> = ::std::result::Result<T, Error>;
impl fmt::Display for LuaError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self {
&LuaError::SyntaxError(ref msg) => write!(fmt, "Lua syntax error: {}", msg),
&LuaError::IncompleteStatement(ref msg) => {
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::SyntaxError(ref msg) => write!(fmt, "Lua syntax error: {}", msg),
Error::IncompleteStatement(ref msg) => {
write!(fmt, "Lua syntax error (incomplete statement): {}", msg)
}
&LuaError::RuntimeError(ref msg) => write!(fmt, "Lua runtime error: {}", msg),
&LuaError::ErrorError(ref msg) => write!(fmt, "Lua error in error handler: {}", msg),
&LuaError::ToLuaConversionError(ref msg) => {
Error::RuntimeError(ref msg) => write!(fmt, "Lua runtime error: {}", msg),
Error::ErrorError(ref msg) => write!(fmt, "Lua error in error handler: {}", msg),
Error::ToLuaConversionError(ref msg) => {
write!(fmt, "Error converting rust type to lua: {}", msg)
}
&LuaError::FromLuaConversionError(ref msg) => {
Error::FromLuaConversionError(ref msg) => {
write!(fmt, "Error converting lua type to rust: {}", msg)
}
&LuaError::CoroutineInactive => write!(fmt, "Cannot resume inactive coroutine"),
&LuaError::UserDataTypeMismatch => write!(fmt, "Userdata not expected type"),
&LuaError::UserDataBorrowError => write!(fmt, "Userdata already mutably borrowed"),
&LuaError::UserDataBorrowMutError => write!(fmt, "Userdata already borrowed"),
&LuaError::CallbackError(ref msg, _) => {
Error::CoroutineInactive => write!(fmt, "Cannot resume inactive coroutine"),
Error::UserDataTypeMismatch => write!(fmt, "Userdata not expected type"),
Error::UserDataBorrowError => write!(fmt, "Userdata already mutably borrowed"),
Error::UserDataBorrowMutError => write!(fmt, "Userdata already borrowed"),
Error::CallbackError(ref msg, _) => {
write!(fmt, "Error during lua callback: {}", msg)
}
&LuaError::ExternalError(ref err) => err.fmt(fmt),
Error::ExternalError(ref err) => err.fmt(fmt),
}
}
}
impl Error for LuaError {
impl error::Error for Error {
fn description(&self) -> &str {
match self {
&LuaError::SyntaxError(_) => "lua syntax error",
&LuaError::IncompleteStatement(_) => "lua incomplete statement",
&LuaError::RuntimeError(_) => "lua runtime error",
&LuaError::ErrorError(_) => "lua error handling error",
&LuaError::ToLuaConversionError(_) => "conversion error to lua",
&LuaError::FromLuaConversionError(_) => "conversion error from lua",
&LuaError::CoroutineInactive => "lua coroutine inactive",
&LuaError::UserDataTypeMismatch => "lua userdata type mismatch",
&LuaError::UserDataBorrowError => "lua userdata already mutably borrowed",
&LuaError::UserDataBorrowMutError => "lua userdata already borrowed",
&LuaError::CallbackError(_, _) => "lua callback error",
&LuaError::ExternalError(ref err) => err.description(),
match *self {
Error::SyntaxError(_) => "lua syntax error",
Error::IncompleteStatement(_) => "lua incomplete statement",
Error::RuntimeError(_) => "lua runtime error",
Error::ErrorError(_) => "lua error handling error",
Error::ToLuaConversionError(_) => "conversion error to lua",
Error::FromLuaConversionError(_) => "conversion error from lua",
Error::CoroutineInactive => "lua coroutine inactive",
Error::UserDataTypeMismatch => "lua userdata type mismatch",
Error::UserDataBorrowError => "lua userdata already mutably borrowed",
Error::UserDataBorrowMutError => "lua userdata already borrowed",
Error::CallbackError(_, _) => "lua callback error",
Error::ExternalError(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&Error> {
match self {
&LuaError::CallbackError(_, ref cause) => Some(cause.as_ref()),
&LuaError::ExternalError(ref err) => err.cause(),
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::CallbackError(_, ref cause) => Some(cause.as_ref()),
Error::ExternalError(ref err) => err.cause(),
_ => None,
}
}
}
impl LuaError {
pub fn external<T: 'static + Error + Send + Sync>(err: T) -> LuaError {
LuaError::ExternalError(Arc::new(err))
impl Error {
pub fn external<T: 'static + error::Error + Send + Sync>(err: T) -> Error {
Error::ExternalError(Arc::new(err))
}
}
pub trait LuaExternalError {
fn to_lua_err(self) -> LuaError;
fn to_lua_err(self) -> Error;
}
impl<E> LuaExternalError for E
where
E: Into<Box<Error + Send + Sync>>,
E: Into<Box<error::Error + Send + Sync>>,
{
fn to_lua_err(self) -> LuaError {
fn to_lua_err(self) -> Error {
#[derive(Debug)]
struct WrapError(Box<Error + Send + Sync>);
struct WrapError(Box<error::Error + Send + Sync>);
impl fmt::Display for WrapError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@ -113,25 +112,25 @@ where
}
}
impl Error for WrapError {
impl error::Error for WrapError {
fn description(&self) -> &str {
self.0.description()
}
}
LuaError::external(WrapError(self.into()))
Error::external(WrapError(self.into()))
}
}
pub trait LuaExternalResult<T> {
fn to_lua_err(self) -> LuaResult<T>;
fn to_lua_err(self) -> Result<T>;
}
impl<T, E> LuaExternalResult<T> for Result<T, E>
impl<T, E> LuaExternalResult<T> for ::std::result::Result<T, E>
where
E: LuaExternalError,
{
fn to_lua_err(self) -> LuaResult<T> {
fn to_lua_err(self) -> Result<T> {
self.map_err(|e| e.to_lua_err())
}
}

File diff suppressed because it is too large Load Diff

View File

@ -4,22 +4,22 @@ use error::*;
use lua::*;
impl<'lua> ToLuaMulti<'lua> for () {
fn to_lua_multi(self, _: &'lua Lua) -> LuaResult<LuaMultiValue> {
Ok(LuaMultiValue::new())
fn to_lua_multi(self, _: &'lua Lua) -> Result<MultiValue> {
Ok(MultiValue::new())
}
}
impl<'lua> FromLuaMulti<'lua> for () {
fn from_lua_multi(_: LuaMultiValue, _: &'lua Lua) -> LuaResult<Self> {
fn from_lua_multi(_: MultiValue, _: &'lua Lua) -> Result<Self> {
Ok(())
}
}
/// Result is convertible to `LuaMultiValue` following the common lua idiom of returning the result
/// Result is convertible to `MultiValue` following the common lua idiom of returning the result
/// on success, or in the case of an error, returning nil followed by the error
impl<'lua, T: ToLua<'lua>, E: ToLua<'lua>> ToLuaMulti<'lua> for Result<T, E> {
fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
let mut result = LuaMultiValue::new();
impl<'lua, T: ToLua<'lua>, E: ToLua<'lua>> ToLuaMulti<'lua> for ::std::result::Result<T, E> {
fn to_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
let mut result = MultiValue::new();
match self {
Ok(v) => result.push_back(v.to_lua(lua)?),
@ -34,27 +34,27 @@ impl<'lua, T: ToLua<'lua>, E: ToLua<'lua>> ToLuaMulti<'lua> for Result<T, E> {
}
impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for T {
fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
let mut v = LuaMultiValue::new();
fn to_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
let mut v = MultiValue::new();
v.push_back(self.to_lua(lua)?);
Ok(v)
}
}
impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for T {
fn from_lua_multi(mut values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
Ok(T::from_lua(values.pop_front().unwrap_or(LuaNil), lua)?)
}
}
impl<'lua> ToLuaMulti<'lua> for LuaMultiValue<'lua> {
fn to_lua_multi(self, _: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> {
fn to_lua_multi(self, _: &'lua Lua) -> Result<MultiValue<'lua>> {
Ok(self)
}
}
impl<'lua> FromLuaMulti<'lua> for LuaMultiValue<'lua> {
fn from_lua_multi(values: LuaMultiValue<'lua>, _: &'lua Lua) -> LuaResult<Self> {
impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> {
fn from_lua_multi(values: MultiValue<'lua>, _: &'lua Lua) -> Result<Self> {
Ok(values)
}
}
@ -63,44 +63,44 @@ impl<'lua> FromLuaMulti<'lua> for LuaMultiValue<'lua> {
/// the values is all the same and the number of values is defined at runtime. This can be included
/// in an hlist when unpacking, but must be the final entry, and will consume the rest of the
/// parameters given.
pub struct LuaVariadic<T>(pub Vec<T>);
pub struct Variadic<T>(pub Vec<T>);
impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for LuaVariadic<T> {
fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for Variadic<T> {
fn to_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
self.0.into_iter().map(|e| e.to_lua(lua)).collect()
}
}
impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for LuaVariadic<T> {
fn from_lua_multi(values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic<T> {
fn from_lua_multi(values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
values
.into_iter()
.map(|e| T::from_lua(e, lua))
.collect::<LuaResult<Vec<T>>>()
.map(LuaVariadic)
.collect::<Result<Vec<T>>>()
.map(Variadic)
}
}
impl<'lua> ToLuaMulti<'lua> for HNil {
fn to_lua_multi(self, _: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
Ok(LuaMultiValue::new())
fn to_lua_multi(self, _: &'lua Lua) -> Result<MultiValue<'lua>> {
Ok(MultiValue::new())
}
}
impl<'lua> FromLuaMulti<'lua> for HNil {
fn from_lua_multi(_: LuaMultiValue<'lua>, _: &'lua Lua) -> LuaResult<Self> {
fn from_lua_multi(_: MultiValue<'lua>, _: &'lua Lua) -> Result<Self> {
Ok(HNil)
}
}
impl<'lua, T: ToLuaMulti<'lua>> ToLuaMulti<'lua> for HCons<T, HNil> {
fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
fn to_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
self.0.to_lua_multi(lua)
}
}
impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for HCons<T, HNil> {
fn from_lua_multi(values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua_multi(values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
Ok(HCons(T::from_lua_multi(values, lua)?, HNil))
}
}
@ -108,7 +108,7 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for HCons<T, HNil> {
impl<'lua, H: ToLua<'lua>, A, B> ToLuaMulti<'lua> for HCons<H, HCons<A, B>>
where HCons<A, B>: ToLuaMulti<'lua>
{
fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult<LuaMultiValue<'lua>> {
fn to_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>> {
let mut results = self.1.to_lua_multi(lua)?;
results.push_front(self.0.to_lua(lua)?);
Ok(results)
@ -118,7 +118,7 @@ impl<'lua, H: ToLua<'lua>, A, B> ToLuaMulti<'lua> for HCons<H, HCons<A, B>>
impl<'lua, H: FromLua<'lua>, A, B> FromLuaMulti<'lua> for HCons<H, HCons<A, B>>
where HCons<A, B>: FromLuaMulti<'lua>
{
fn from_lua_multi(mut values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult<Self> {
fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result<Self> {
let val = H::from_lua(values.pop_front().unwrap_or(LuaNil), lua)?;
let res = HCons::<A, B>::from_lua_multi(values, lua)?;
Ok(HCons(val, res))

View File

@ -1,6 +1,5 @@
use std::fmt;
use std::result::Result;
use std::error::Error;
use std::error;
use std::panic::catch_unwind;
use std::os::raw::c_void;
@ -38,7 +37,7 @@ fn test_exec() {
).unwrap();
assert_eq!(globals.get::<_, String>("res").unwrap(), "foobar");
let module: LuaTable = lua.exec(
let module: Table = lua.exec(
r#"
local module = {}
@ -53,7 +52,7 @@ fn test_exec() {
assert!(module.contains_key("func").unwrap());
assert_eq!(
module
.get::<_, LuaFunction>("func")
.get::<_, Function>("func")
.unwrap()
.call::<_, String>(())
.unwrap(),
@ -68,7 +67,7 @@ fn test_eval() {
assert_eq!(lua.eval::<bool>("false == false", None).unwrap(), true);
assert_eq!(lua.eval::<i32>("return 1 + 2", None).unwrap(), 3);
match lua.eval::<()>("if true then", None) {
Err(LuaError::IncompleteStatement(_)) => {}
Err(Error::IncompleteStatement(_)) => {}
r => panic!("expected IncompleteStatement, got {:?}", r),
}
}
@ -79,8 +78,8 @@ fn test_table() {
let globals = lua.globals();
globals.set("table", lua.create_table()).unwrap();
let table1: LuaTable = globals.get("table").unwrap();
let table2: LuaTable = globals.get("table").unwrap();
let table1: Table = globals.get("table").unwrap();
let table2: Table = globals.get("table").unwrap();
table1.set("foo", "bar").unwrap();
table2.set("baz", "baf").unwrap();
@ -97,16 +96,16 @@ fn test_table() {
None,
).unwrap();
let table1 = globals.get::<_, LuaTable>("table1").unwrap();
let table2 = globals.get::<_, LuaTable>("table2").unwrap();
let table3 = globals.get::<_, LuaTable>("table3").unwrap();
let table1 = globals.get::<_, Table>("table1").unwrap();
let table2 = globals.get::<_, Table>("table2").unwrap();
let table3 = globals.get::<_, Table>("table3").unwrap();
assert_eq!(table1.len().unwrap(), 5);
assert_eq!(
table1
.clone()
.pairs()
.collect::<LuaResult<Vec<(i64, i64)>>>()
.collect::<Result<Vec<(i64, i64)>>>()
.unwrap(),
vec![(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
);
@ -114,7 +113,7 @@ fn test_table() {
table1
.clone()
.sequence_values()
.collect::<LuaResult<Vec<i64>>>()
.collect::<Result<Vec<i64>>>()
.unwrap(),
vec![1, 2, 3, 4, 5]
);
@ -124,14 +123,14 @@ fn test_table() {
table2
.clone()
.pairs()
.collect::<LuaResult<Vec<(i64, i64)>>>()
.collect::<Result<Vec<(i64, i64)>>>()
.unwrap(),
vec![]
);
assert_eq!(
table2
.sequence_values()
.collect::<LuaResult<Vec<i64>>>()
.collect::<Result<Vec<i64>>>()
.unwrap(),
vec![]
);
@ -140,7 +139,7 @@ fn test_table() {
assert_eq!(
table3
.sequence_values()
.collect::<LuaResult<Vec<i64>>>()
.collect::<Result<Vec<i64>>>()
.unwrap(),
vec![1, 2]
);
@ -151,11 +150,11 @@ fn test_table() {
lua.create_sequence_from(vec![1, 2, 3, 4, 5]).unwrap(),
)
.unwrap();
let table4 = globals.get::<_, LuaTable>("table4").unwrap();
let table4 = globals.get::<_, Table>("table4").unwrap();
assert_eq!(
table4
.pairs()
.collect::<LuaResult<Vec<(i64, i64)>>>()
.collect::<Result<Vec<(i64, i64)>>>()
.unwrap(),
vec![(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
);
@ -174,7 +173,7 @@ fn test_function() {
None,
).unwrap();
let concat = globals.get::<_, LuaFunction>("concat").unwrap();
let concat = globals.get::<_, Function>("concat").unwrap();
assert_eq!(
concat.call::<_, String>(hlist!["foo", "bar"]).unwrap(),
"foobar"
@ -198,7 +197,7 @@ fn test_bind() {
None,
).unwrap();
let mut concat = globals.get::<_, LuaFunction>("concat").unwrap();
let mut concat = globals.get::<_, Function>("concat").unwrap();
concat = concat.bind("foo").unwrap();
concat = concat.bind("bar").unwrap();
concat = concat.bind(hlist!["baz", "baf"]).unwrap();
@ -226,7 +225,7 @@ fn test_rust_function() {
None,
).unwrap();
let lua_function = globals.get::<_, LuaFunction>("lua_function").unwrap();
let lua_function = globals.get::<_, Function>("lua_function").unwrap();
let rust_function = lua.create_function(|lua, _| {
captured_var = 42;
lua.pack("hello")
@ -243,8 +242,8 @@ fn test_user_data() {
struct UserData1(i64);
struct UserData2(Box<i64>);
impl LuaUserDataType for UserData1 {};
impl LuaUserDataType for UserData2 {};
impl UserData for UserData1 {};
impl UserData for UserData2 {};
let lua = Lua::new();
@ -262,10 +261,10 @@ fn test_user_data() {
#[test]
fn test_methods() {
struct UserData(i64);
struct MyUserData(i64);
impl LuaUserDataType for UserData {
fn add_methods(methods: &mut LuaUserDataMethods<Self>) {
impl UserData for MyUserData {
fn add_methods(methods: &mut UserDataMethods<Self>) {
methods.add_method("get_value", |lua, data, _| lua.pack(data.0));
methods.add_method_mut("set_value", |lua, data, args| {
data.0 = lua.unpack(args)?;
@ -276,7 +275,7 @@ fn test_methods() {
let lua = Lua::new();
let globals = lua.globals();
let userdata = lua.create_userdata(UserData(42));
let userdata = lua.create_userdata(MyUserData(42));
globals.set("userdata", userdata.clone()).unwrap();
lua.exec::<()>(
r#"
@ -290,10 +289,10 @@ fn test_methods() {
"#,
None,
).unwrap();
let get = globals.get::<_, LuaFunction>("get_it").unwrap();
let set = globals.get::<_, LuaFunction>("set_it").unwrap();
let get = globals.get::<_, Function>("get_it").unwrap();
let set = globals.get::<_, Function>("set_it").unwrap();
assert_eq!(get.call::<_, i64>(()).unwrap(), 42);
userdata.borrow_mut::<UserData>().unwrap().0 = 64;
userdata.borrow_mut::<MyUserData>().unwrap().0 = 64;
assert_eq!(get.call::<_, i64>(()).unwrap(), 64);
set.call::<_, ()>(100).unwrap();
assert_eq!(get.call::<_, i64>(()).unwrap(), 100);
@ -302,20 +301,20 @@ fn test_methods() {
#[test]
fn test_metamethods() {
#[derive(Copy, Clone)]
struct UserData(i64);
struct MyUserData(i64);
impl LuaUserDataType for UserData {
fn add_methods(methods: &mut LuaUserDataMethods<Self>) {
impl UserData for MyUserData {
fn add_methods(methods: &mut UserDataMethods<Self>) {
methods.add_method("get", |lua, data, _| lua.pack(data.0));
methods.add_meta_function(LuaMetaMethod::Add, |lua, args| {
let hlist_pat![lhs, rhs] = lua.unpack::<HList![UserData, UserData]>(args)?;
lua.pack(UserData(lhs.0 + rhs.0))
methods.add_meta_function(MetaMethod::Add, |lua, args| {
let hlist_pat![lhs, rhs] = lua.unpack::<HList![MyUserData, MyUserData]>(args)?;
lua.pack(MyUserData(lhs.0 + rhs.0))
});
methods.add_meta_function(LuaMetaMethod::Sub, |lua, args| {
let hlist_pat![lhs, rhs] = lua.unpack::<HList![UserData, UserData]>(args)?;
lua.pack(UserData(lhs.0 - rhs.0))
methods.add_meta_function(MetaMethod::Sub, |lua, args| {
let hlist_pat![lhs, rhs] = lua.unpack::<HList![MyUserData, MyUserData]>(args)?;
lua.pack(MyUserData(lhs.0 - rhs.0))
});
methods.add_meta_method(LuaMetaMethod::Index, |lua, data, args| {
methods.add_meta_method(MetaMethod::Index, |lua, data, args| {
let index = lua.unpack::<LuaString>(args)?;
if index.to_str()? == "inner" {
lua.pack(data.0)
@ -328,16 +327,16 @@ fn test_metamethods() {
let lua = Lua::new();
let globals = lua.globals();
globals.set("userdata1", UserData(7)).unwrap();
globals.set("userdata2", UserData(3)).unwrap();
globals.set("userdata1", MyUserData(7)).unwrap();
globals.set("userdata2", MyUserData(3)).unwrap();
assert_eq!(
lua.eval::<UserData>("userdata1 + userdata2", None)
lua.eval::<MyUserData>("userdata1 + userdata2", None)
.unwrap()
.0,
10
);
assert_eq!(
lua.eval::<UserData>("userdata1 - userdata2", None)
lua.eval::<MyUserData>("userdata1 - userdata2", None)
.unwrap()
.0,
4
@ -363,8 +362,8 @@ fn test_scope() {
// Make sure that table gets do not borrow the table, but instead just borrow lua.
let tin;
{
let touter = globals.get::<_, LuaTable>("touter").unwrap();
tin = touter.get::<_, LuaTable>("tin").unwrap();
let touter = globals.get::<_, Table>("touter").unwrap();
tin = touter.get::<_, Table>("tin").unwrap();
}
assert_eq!(tin.get::<_, i64>(1).unwrap(), 1);
@ -373,10 +372,10 @@ fn test_scope() {
// Should not compile, don't know how to test that
// struct UserData;
// impl LuaUserDataType for UserData {};
// impl UserData for UserData {};
// let userdata_ref;
// {
// let touter = globals.get::<_, LuaTable>("touter").unwrap();
// let touter = globals.get::<_, Table>("touter").unwrap();
// touter.set("userdata", lua.create_userdata(UserData).unwrap()).unwrap();
// let userdata = touter.get::<_, LuaUserData>("userdata").unwrap();
// userdata_ref = userdata.borrow::<UserData>();
@ -400,8 +399,8 @@ fn test_lua_multi() {
None,
).unwrap();
let concat = globals.get::<_, LuaFunction>("concat").unwrap();
let mreturn = globals.get::<_, LuaFunction>("mreturn").unwrap();
let concat = globals.get::<_, Function>("concat").unwrap();
let mreturn = globals.get::<_, Function>("mreturn").unwrap();
assert_eq!(
concat.call::<_, String>(hlist!["foo", "bar"]).unwrap(),
@ -409,8 +408,8 @@ fn test_lua_multi() {
);
let hlist_pat![a, b] = mreturn.call::<_, HList![u64, u64]>(hlist![]).unwrap();
assert_eq!((a, b), (1, 2));
let hlist_pat![a, b, LuaVariadic(v)] =
mreturn.call::<_, HList![u64, u64, LuaVariadic<u64>]>(hlist![]).unwrap();
let hlist_pat![a, b, Variadic(v)] =
mreturn.call::<_, HList![u64, u64, Variadic<u64>]>(hlist![]).unwrap();
assert_eq!((a, b), (1, 2));
assert_eq!(v, vec![3, 4, 5, 6]);
}
@ -439,17 +438,17 @@ fn test_error() {
pub struct TestError;
impl fmt::Display for TestError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "test error")
}
}
impl Error for TestError {
impl error::Error for TestError {
fn description(&self) -> &str {
"test error"
}
fn cause(&self) -> Option<&Error> {
fn cause(&self) -> Option<&error::Error> {
None
}
}
@ -514,44 +513,44 @@ fn test_error() {
.set("rust_error_function", rust_error_function)
.unwrap();
let no_error = globals.get::<_, LuaFunction>("no_error").unwrap();
let lua_error = globals.get::<_, LuaFunction>("lua_error").unwrap();
let rust_error = globals.get::<_, LuaFunction>("rust_error").unwrap();
let return_error = globals.get::<_, LuaFunction>("return_error").unwrap();
let no_error = globals.get::<_, Function>("no_error").unwrap();
let lua_error = globals.get::<_, Function>("lua_error").unwrap();
let rust_error = globals.get::<_, Function>("rust_error").unwrap();
let return_error = globals.get::<_, Function>("return_error").unwrap();
let return_string_error = globals
.get::<_, LuaFunction>("return_string_error")
.get::<_, Function>("return_string_error")
.unwrap();
let test_pcall = globals.get::<_, LuaFunction>("test_pcall").unwrap();
let test_pcall = globals.get::<_, Function>("test_pcall").unwrap();
let understand_recursion = globals
.get::<_, LuaFunction>("understand_recursion")
.get::<_, Function>("understand_recursion")
.unwrap();
assert!(no_error.call::<_, ()>(()).is_ok());
match lua_error.call::<_, ()>(()) {
Err(LuaError::RuntimeError(_)) => {}
Err(Error::RuntimeError(_)) => {}
Err(_) => panic!("error is not RuntimeError kind"),
_ => panic!("error not returned"),
}
match rust_error.call::<_, ()>(()) {
Err(LuaError::CallbackError(_, _)) => {}
Err(Error::CallbackError(_, _)) => {}
Err(_) => panic!("error is not CallbackError kind"),
_ => panic!("error not returned"),
}
match return_error.call::<_, LuaValue>(()) {
Ok(LuaValue::Error(_)) => {}
_ => panic!("LuaValue::Error not returned"),
match return_error.call::<_, Value>(()) {
Ok(Value::Error(_)) => {}
_ => panic!("Value::Error not returned"),
}
assert!(return_string_error.call::<_, LuaError>(()).is_ok());
assert!(return_string_error.call::<_, Error>(()).is_ok());
match lua.eval::<()>("if youre happy and you know it syntax error", None) {
Err(LuaError::SyntaxError(_)) => {}
Err(Error::SyntaxError(_)) => {}
Err(_) => panic!("error is not LuaSyntaxError::Syntax kind"),
_ => panic!("error not returned"),
}
match lua.eval::<()>("function i_will_finish_what_i()", None) {
Err(LuaError::IncompleteStatement(_)) => {}
Err(Error::IncompleteStatement(_)) => {}
Err(_) => panic!("error is not LuaSyntaxError::IncompleteStatement kind"),
_ => panic!("error not returned"),
}
@ -560,7 +559,7 @@ fn test_error() {
assert!(understand_recursion.call::<_, ()>(()).is_err());
match catch_unwind(|| -> LuaResult<()> {
match catch_unwind(|| -> Result<()> {
let lua = Lua::new();
let globals = lua.globals();
@ -577,7 +576,7 @@ fn test_error() {
});
globals.set("rust_panic_function", rust_panic_function)?;
let rust_panic = globals.get::<_, LuaFunction>("rust_panic")?;
let rust_panic = globals.get::<_, Function>("rust_panic")?;
rust_panic.call::<_, ()>(())
}) {
@ -586,7 +585,7 @@ fn test_error() {
Err(_) => {}
};
match catch_unwind(|| -> LuaResult<()> {
match catch_unwind(|| -> Result<()> {
let lua = Lua::new();
let globals = lua.globals();
@ -603,7 +602,7 @@ fn test_error() {
});
globals.set("rust_panic_function", rust_panic_function)?;
let rust_panic = globals.get::<_, LuaFunction>("rust_panic")?;
let rust_panic = globals.get::<_, Function>("rust_panic")?;
rust_panic.call::<_, ()>(())
}) {
@ -617,7 +616,7 @@ fn test_error() {
fn test_thread() {
let lua = Lua::new();
let thread = lua.create_thread(
lua.eval::<LuaFunction>(
lua.eval::<Function>(
r#"
function (s)
local sum = s
@ -631,20 +630,20 @@ fn test_thread() {
).unwrap(),
);
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.status(), ThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(0).unwrap(), 0);
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.status(), ThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(1).unwrap(), 1);
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.status(), ThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(2).unwrap(), 3);
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.status(), ThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(3).unwrap(), 6);
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.status(), ThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(4).unwrap(), 10);
assert_eq!(thread.status(), LuaThreadStatus::Dead);
assert_eq!(thread.status(), ThreadStatus::Dead);
let accumulate = lua.create_thread(
lua.eval::<LuaFunction>(
lua.eval::<Function>(
r#"
function (sum)
while true do
@ -660,11 +659,11 @@ fn test_thread() {
accumulate.resume::<_, ()>(i).unwrap();
}
assert_eq!(accumulate.resume::<_, i64>(4).unwrap(), 10);
assert_eq!(accumulate.status(), LuaThreadStatus::Active);
assert_eq!(accumulate.status(), ThreadStatus::Active);
assert!(accumulate.resume::<_, ()>("error").is_err());
assert_eq!(accumulate.status(), LuaThreadStatus::Error);
assert_eq!(accumulate.status(), ThreadStatus::Error);
let thread = lua.eval::<LuaThread>(
let thread = lua.eval::<Thread>(
r#"
coroutine.create(function ()
while true do
@ -674,10 +673,10 @@ fn test_thread() {
"#,
None,
).unwrap();
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.status(), ThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(()).unwrap(), 42);
let thread: LuaThread = lua.eval(
let thread: Thread = lua.eval(
r#"
coroutine.create(function(arg)
assert(arg == 42)
@ -693,7 +692,7 @@ fn test_thread() {
assert_eq!(thread.resume::<_, u32>(43).unwrap(), 987);
match thread.resume::<_, u32>(()) {
Err(LuaError::CoroutineInactive) => {}
Err(Error::CoroutineInactive) => {}
Err(_) => panic!("resuming dead coroutine error is not CoroutineInactive kind"),
_ => panic!("resuming dead coroutine did not return error"),
}
@ -712,11 +711,11 @@ fn test_lightuserdata() {
None,
).unwrap();
let res = globals
.get::<_, LuaFunction>("id")
.get::<_, Function>("id")
.unwrap()
.call::<_, LuaLightUserData>(LuaLightUserData(42 as *mut c_void))
.call::<_, LightUserData>(LightUserData(42 as *mut c_void))
.unwrap();
assert_eq!(res, LuaLightUserData(42 as *mut c_void));
assert_eq!(res, LightUserData(42 as *mut c_void));
}
#[test]
@ -741,7 +740,7 @@ fn test_table_error() {
None,
).unwrap();
let bad_table: LuaTable = globals.get("table").unwrap();
let bad_table: Table = globals.get("table").unwrap();
assert!(bad_table.set(1, 1).is_err());
assert!(bad_table.get::<_, i32>(1).is_err());
assert!(bad_table.len().is_err());
@ -756,11 +755,11 @@ fn test_result_conversions() {
let globals = lua.globals();
let err = lua.create_function(|lua, _| {
lua.pack(Result::Err::<String, _>(
lua.pack(Err::<String, _>(
"only through failure can we succeed".to_lua_err(),
))
});
let ok = lua.create_function(|lua, _| lua.pack(Result::Ok::<_, LuaError>("!".to_owned())));
let ok = lua.create_function(|lua, _| lua.pack(Ok::<_, Error>("!".to_owned())));
globals.set("err", err).unwrap();
globals.set("ok", ok).unwrap();

View File

@ -8,7 +8,7 @@ use std::os::raw::{c_char, c_int, c_void};
use std::panic::{catch_unwind, resume_unwind, UnwindSafe};
use ffi;
use error::{LuaResult, LuaError};
use error::{Result, Error};
macro_rules! cstr {
($s:expr) => (
@ -114,9 +114,9 @@ pub unsafe fn stack_err_guard<F, R>(
state: *mut ffi::lua_State,
change: c_int,
op: F,
) -> LuaResult<R>
) -> Result<R>
where
F: FnOnce() -> LuaResult<R>,
F: FnOnce() -> Result<R>,
{
let expected = ffi::lua_gettop(state) + change;
lua_assert!(
@ -161,9 +161,9 @@ pub unsafe fn error_guard<F, R>(
state: *mut ffi::lua_State,
nargs: c_int,
func: F,
) -> LuaResult<R>
) -> Result<R>
where
F: FnOnce(*mut ffi::lua_State) -> LuaResult<R> + UnwindSafe,
F: FnOnce(*mut ffi::lua_State) -> Result<R> + UnwindSafe,
{
unsafe extern "C" fn call_impl<F>(state: *mut ffi::lua_State) -> c_int
where
@ -179,7 +179,7 @@ where
state: *mut ffi::lua_State,
nargs: c_int,
mut func: F,
) -> LuaResult<()>
) -> Result<()>
where
F: FnOnce(*mut ffi::lua_State) -> c_int,
{
@ -209,7 +209,7 @@ where
// stack continues the panic. If the error on the top of the stack is actually
// a WrappedError, just returns it. Otherwise, interprets the error as the
// appropriate lua error.
pub unsafe fn handle_error(state: *mut ffi::lua_State, err: c_int) -> LuaResult<()> {
pub unsafe fn handle_error(state: *mut ffi::lua_State, err: c_int) -> Result<()> {
if err == ffi::LUA_OK || err == ffi::LUA_YIELD {
Ok(())
} else {
@ -238,17 +238,17 @@ pub unsafe fn handle_error(state: *mut ffi::lua_State, err: c_int) -> LuaResult<
ffi::lua_pop(state, 1);
Err(match err {
ffi::LUA_ERRRUN => LuaError::RuntimeError(err_string),
ffi::LUA_ERRRUN => Error::RuntimeError(err_string),
ffi::LUA_ERRSYNTAX => {
// This seems terrible, but as far as I can tell, this is exactly what the stock
// lua repl does.
if err_string.ends_with("<eof>") {
LuaError::IncompleteStatement(err_string)
Error::IncompleteStatement(err_string)
} else {
LuaError::SyntaxError(err_string)
Error::SyntaxError(err_string)
}
}
ffi::LUA_ERRERR => LuaError::ErrorError(err_string),
ffi::LUA_ERRERR => Error::ErrorError(err_string),
ffi::LUA_ERRMEM => {
// This is not impossible to hit, but this library is not set up
// to handle this properly. Lua does a longjmp on out of memory
@ -310,7 +310,7 @@ pub unsafe extern "C" fn userdata_destructor<T>(state: *mut ffi::lua_State) -> c
// the rust side, it will resume the panic.
pub unsafe fn callback_error<R, F>(state: *mut ffi::lua_State, f: F) -> R
where
F: FnOnce() -> LuaResult<R> + UnwindSafe,
F: FnOnce() -> Result<R> + UnwindSafe,
{
match catch_unwind(f) {
Ok(Ok(r)) => r,
@ -326,7 +326,7 @@ where
}
// ffi::lua_pcall with a message handler that gives a nice traceback. If the
// caught error is actually a LuaError, will simply pass the error along. Does
// caught error is actually a Error, will simply pass the error along. Does
// not call checkstack, and uses 2 extra stack spaces.
pub unsafe fn pcall_with_traceback(
state: *mut ffi::lua_State,
@ -340,7 +340,7 @@ pub unsafe fn pcall_with_traceback(
.to_str()
.unwrap_or_else(|_| "<could not capture traceback>")
.to_owned();
push_wrapped_error(state, LuaError::CallbackError(traceback, Arc::new(error)));
push_wrapped_error(state, Error::CallbackError(traceback, Arc::new(error)));
} else if !is_wrapped_panic(state, 1) {
let s = ffi::lua_tolstring(state, 1, ptr::null_mut());
if !s.is_null() {
@ -373,7 +373,7 @@ pub unsafe fn resume_with_traceback(
.to_str()
.unwrap_or_else(|_| "<could not capture traceback>")
.to_owned();
push_wrapped_error(from, LuaError::CallbackError(traceback, Arc::new(error)));
push_wrapped_error(from, Error::CallbackError(traceback, Arc::new(error)));
} else if !is_wrapped_panic(state, 1) {
let s = ffi::lua_tolstring(state, 1, ptr::null_mut());
if !s.is_null() {
@ -443,11 +443,11 @@ pub unsafe fn main_state(state: *mut ffi::lua_State) -> *mut ffi::lua_State {
state
}
pub struct WrappedError(pub LuaError);
pub struct WrappedError(pub Error);
pub struct WrappedPanic(pub Option<Box<Any + Send>>);
// Pushes a WrappedError::Error to the top of the stack
pub unsafe fn push_wrapped_error(state: *mut ffi::lua_State, err: LuaError) {
pub unsafe fn push_wrapped_error(state: *mut ffi::lua_State, err: Error) {
unsafe extern "C" fn error_tostring(state: *mut ffi::lua_State) -> c_int {
callback_error(state, || if is_wrapped_error(state, -1) {
let error = &*get_userdata::<WrappedError>(state, -1);
@ -457,8 +457,8 @@ pub unsafe fn push_wrapped_error(state: *mut ffi::lua_State, err: LuaError) {
Ok(1)
} else {
Err(LuaError::FromLuaConversionError(
"internal error: userdata mismatch in LuaError metamethod"
Err(Error::FromLuaConversionError(
"internal error: userdata mismatch in Error metamethod"
.to_owned(),
))
})
@ -534,7 +534,7 @@ pub unsafe fn push_wrapped_panic(state: *mut ffi::lua_State, panic: Box<Any + Se
// Pops a WrappedError off of the top of the stack, if it is a WrappedError. If
// it is not a WrappedError, returns None and does not pop anything.
pub unsafe fn pop_wrapped_error(state: *mut ffi::lua_State) -> Option<LuaError> {
pub unsafe fn pop_wrapped_error(state: *mut ffi::lua_State) -> Option<Error> {
if ffi::lua_gettop(state) == 0 || !is_wrapped_error(state, -1) {
None
} else {