From 9df7727eaaf83799cc538a451a6a5a6288ff27cd Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Tue, 18 Jul 2017 22:21:12 +0200 Subject: [PATCH 1/6] 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. --- examples/examples.rs | 20 +- examples/repl.rs | 4 +- src/conversion.rs | 178 +++++++++--------- src/error.rs | 107 ++++++----- src/lua.rs | 423 ++++++++++++++++++++++--------------------- src/multi.rs | 56 +++--- src/tests.rs | 185 ++++++++++--------- src/util.rs | 40 ++-- 8 files changed, 508 insertions(+), 505 deletions(-) diff --git a/examples/examples.rs b/examples/examples.rs index 13a4653..5ee0758 100644 --- a/examples/examples.rs +++ b/examples/examples.rs @@ -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::>(args)?.0; + let strings = lua.unpack::>(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) { + impl UserData for Vec2 { + fn add_methods(methods: &mut UserDataMethods) { 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::(params)?; lua.pack(Vec2(vec1.0 + vec2.0, vec1.1 + vec2.1)) }); diff --git a/examples/repl.rs b/examples/repl.rs index cae2465..0d6bf9c 100644 --- a/examples/repl.rs +++ b/examples/repl.rs @@ -20,7 +20,7 @@ fn main() { loop { stdin.read_line(&mut line).unwrap(); - match lua.eval::(&line, None) { + match lua.eval::(&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(); diff --git a/src/conversion.rs b/src/conversion.rs index a27ff25..df1ccad 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -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> { +impl<'lua> ToLua<'lua> for Value<'lua> { + fn to_lua(self, _: &'lua Lua) -> Result> { Ok(self) } } -impl<'lua> FromLua<'lua> for LuaValue<'lua> { - fn from_lua(lua_value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult { +impl<'lua> FromLua<'lua> for Value<'lua> { + fn from_lua(lua_value: Value<'lua>, _: &'lua Lua) -> Result { Ok(lua_value) } } impl<'lua> ToLua<'lua> for LuaString<'lua> { - fn to_lua(self, _: &'lua Lua) -> LuaResult> { - Ok(LuaValue::String(self)) + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::String(self)) } } impl<'lua> FromLua<'lua> for LuaString<'lua> { - fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult> { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result> { lua.coerce_string(value) } } -impl<'lua> ToLua<'lua> for LuaTable<'lua> { - fn to_lua(self, _: &'lua Lua) -> LuaResult { - Ok(LuaValue::Table(self)) +impl<'lua> ToLua<'lua> for Table<'lua> { + fn to_lua(self, _: &'lua Lua) -> Result { + Ok(Value::Table(self)) } } -impl<'lua> FromLua<'lua> for LuaTable<'lua> { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult> { +impl<'lua> FromLua<'lua> for Table<'lua> { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result> { 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> { - Ok(LuaValue::Function(self)) +impl<'lua> ToLua<'lua> for Function<'lua> { + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::Function(self)) } } -impl<'lua> FromLua<'lua> for LuaFunction<'lua> { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult> { +impl<'lua> FromLua<'lua> for Function<'lua> { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result> { 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> { - Ok(LuaValue::Thread(self)) +impl<'lua> ToLua<'lua> for Thread<'lua> { + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::Thread(self)) } } -impl<'lua> FromLua<'lua> for LuaThread<'lua> { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult> { +impl<'lua> FromLua<'lua> for Thread<'lua> { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result> { 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> { - Ok(LuaValue::UserData(self)) +impl<'lua> ToLua<'lua> for AnyUserData<'lua> { + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::UserData(self)) } } -impl<'lua> FromLua<'lua> for LuaUserData<'lua> { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult> { +impl<'lua> FromLua<'lua> for AnyUserData<'lua> { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result> { 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> { - Ok(LuaValue::UserData(lua.create_userdata(self))) +impl<'lua, T: UserData> ToLua<'lua> for T { + fn to_lua(self, lua: &'lua Lua) -> Result> { + 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 { +impl<'lua, T: UserData + Copy> FromLua<'lua> for T { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result { match value { - LuaValue::UserData(ud) => Ok(*ud.borrow::()?), - _ => Err(LuaError::FromLuaConversionError( + Value::UserData(ud) => Ok(*ud.borrow::()?), + _ => Err(Error::FromLuaConversionError( "cannot convert lua value to userdata".to_owned(), )), } } } -impl<'lua> ToLua<'lua> for LuaError { - fn to_lua(self, _: &'lua Lua) -> LuaResult> { - Ok(LuaValue::Error(self)) +impl<'lua> ToLua<'lua> for Error { + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::Error(self)) } } -impl<'lua> FromLua<'lua> for LuaError { - fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult { +impl<'lua> FromLua<'lua> for Error { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { 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(|_| "".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> { - Ok(LuaValue::Boolean(self)) + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::Boolean(self)) } } impl<'lua> FromLua<'lua> for bool { - fn from_lua(v: LuaValue, _: &'lua Lua) -> LuaResult { + fn from_lua(v: Value, _: &'lua Lua) -> Result { 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> { - Ok(LuaValue::LightUserData(self)) +impl<'lua> ToLua<'lua> for LightUserData { + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::LightUserData(self)) } } -impl<'lua> FromLua<'lua> for LuaLightUserData { - fn from_lua(v: LuaValue, _: &'lua Lua) -> LuaResult { +impl<'lua> FromLua<'lua> for LightUserData { + fn from_lua(v: Value, _: &'lua Lua) -> Result { 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> { - Ok(LuaValue::String(lua.create_string(&self))) + fn to_lua(self, lua: &'lua Lua) -> Result> { + Ok(Value::String(lua.create_string(&self))) } } impl<'lua> FromLua<'lua> for String { - fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { 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> { - Ok(LuaValue::String(lua.create_string(self))) + fn to_lua(self, lua: &'lua Lua) -> Result> { + 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> { - Ok(LuaValue::Integer(self as LuaInteger)) + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::Integer(self as Integer)) } } impl<'lua> FromLua<'lua> for $x { - fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { 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> { - Ok(LuaValue::Number(self as LuaNumber)) + fn to_lua(self, _: &'lua Lua) -> Result> { + Ok(Value::Number(self as Number)) } } impl<'lua> FromLua<'lua> for $x { - fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { 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 { - fn to_lua(self, lua: &'lua Lua) -> LuaResult> { - Ok(LuaValue::Table(lua.create_sequence_from(self)?)) + fn to_lua(self, lua: &'lua Lua) -> Result> { + Ok(Value::Table(lua.create_sequence_from(self)?)) } } impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Vec { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult { - if let LuaValue::Table(table) = value { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result { + 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 { } impl<'lua, K: Eq + Hash + ToLua<'lua>, V: ToLua<'lua>> ToLua<'lua> for HashMap { - fn to_lua(self, lua: &'lua Lua) -> LuaResult> { - Ok(LuaValue::Table(lua.create_table_from(self)?)) + fn to_lua(self, lua: &'lua Lua) -> Result> { + Ok(Value::Table(lua.create_table_from(self)?)) } } impl<'lua, K: Eq + Hash + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for HashMap { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult { - if let LuaValue::Table(table) = value { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result { + 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 { - fn to_lua(self, lua: &'lua Lua) -> LuaResult> { - Ok(LuaValue::Table(lua.create_table_from(self)?)) + fn to_lua(self, lua: &'lua Lua) -> Result> { + Ok(Value::Table(lua.create_table_from(self)?)) } } impl<'lua, K: Ord + FromLua<'lua>, V: FromLua<'lua>> FromLua<'lua> for BTreeMap { - fn from_lua(value: LuaValue<'lua>, _: &'lua Lua) -> LuaResult { - if let LuaValue::Table(table) = value { + fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result { + 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 { - fn to_lua(self, lua: &'lua Lua) -> LuaResult> { + fn to_lua(self, lua: &'lua Lua) -> Result> { match self { Some(val) => val.to_lua(lua), None => Ok(LuaNil), @@ -293,7 +293,7 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option { } impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option { - fn from_lua(value: LuaValue<'lua>, lua: &'lua Lua) -> LuaResult { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { match value { LuaNil => Ok(None), value => Ok(Some(T::from_lua(value, lua)?)), diff --git a/src/error.rs b/src/error.rs index aa7676e..835d086 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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), + /// 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), /// Any custom external error type, mostly useful for returning external error types from /// callbacks. - ExternalError(Arc), + ExternalError(Arc), } -pub type LuaResult = Result; +pub type Result = ::std::result::Result; -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(err: T) -> LuaError { - LuaError::ExternalError(Arc::new(err)) +impl Error { + pub fn external(err: T) -> Error { + Error::ExternalError(Arc::new(err)) } } pub trait LuaExternalError { - fn to_lua_err(self) -> LuaError; + fn to_lua_err(self) -> Error; } impl LuaExternalError for E where - E: Into>, + E: Into>, { - fn to_lua_err(self) -> LuaError { + fn to_lua_err(self) -> Error { #[derive(Debug)] - struct WrapError(Box); + struct WrapError(Box); 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 { - fn to_lua_err(self) -> LuaResult; + fn to_lua_err(self) -> Result; } -impl LuaExternalResult for Result +impl LuaExternalResult for ::std::result::Result where E: LuaExternalError, { - fn to_lua_err(self) -> LuaResult { + fn to_lua_err(self) -> Result { self.map_err(|e| e.to_lua_err()) } } diff --git a/src/lua.rs b/src/lua.rs index 4ed9bd2..8290e0d 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -16,85 +16,85 @@ use util::*; /// A dynamically typed Lua value. #[derive(Debug, Clone)] -pub enum LuaValue<'lua> { +pub enum Value<'lua> { /// The Lua value `nil`. Nil, /// The Lua value `true` or `false`. Boolean(bool), /// A "light userdata" object, equivalent to a raw pointer. - LightUserData(LuaLightUserData), + LightUserData(LightUserData), /// An integer number. /// - /// Any Lua number convertible to a `LuaInteger` will be represented as this variant. - Integer(LuaInteger), + /// Any Lua number convertible to a `Integer` will be represented as this variant. + Integer(Integer), /// A floating point number. - Number(LuaNumber), + Number(Number), /// An interned string, managed by Lua. /// /// Unlike Rust strings, Lua strings may not be valid UTF-8. String(LuaString<'lua>), /// Reference to a Lua table. - Table(LuaTable<'lua>), + Table(Table<'lua>), /// Reference to a Lua function (or closure). - Function(LuaFunction<'lua>), + Function(Function<'lua>), /// Reference to a Lua thread (or coroutine). - Thread(LuaThread<'lua>), + Thread(Thread<'lua>), /// Reference to a userdata object that holds a custom type which implements - /// `LuaUserDataType`. Special builtin userdata types will be represented as - /// other `LuaValue` variants. - UserData(LuaUserData<'lua>), - /// `LuaError` is a special builtin userdata type. When received from Lua + /// `UserData`. Special builtin userdata types will be represented as + /// other `Value` variants. + UserData(AnyUserData<'lua>), + /// `Error` is a special builtin userdata type. When received from Lua /// it is implicitly cloned. - Error(LuaError), + Error(Error), } -pub use self::LuaValue::Nil as LuaNil; +pub use self::Value::Nil as LuaNil; -/// Trait for types convertible to `LuaValue`. +/// Trait for types convertible to `Value`. pub trait ToLua<'a> { /// Performs the conversion. - fn to_lua(self, lua: &'a Lua) -> LuaResult>; + fn to_lua(self, lua: &'a Lua) -> Result>; } -/// Trait for types convertible from `LuaValue`. +/// Trait for types convertible from `Value`. pub trait FromLua<'a>: Sized { /// Performs the conversion. - fn from_lua(lua_value: LuaValue<'a>, lua: &'a Lua) -> LuaResult; + fn from_lua(lua_value: Value<'a>, lua: &'a Lua) -> Result; } /// Multiple Lua values used for both argument passing and also for multiple return values. #[derive(Debug, Clone)] -pub struct LuaMultiValue<'lua>(VecDeque>); +pub struct MultiValue<'lua>(VecDeque>); -impl<'lua> LuaMultiValue<'lua> { - pub fn new() -> LuaMultiValue<'lua> { - LuaMultiValue(VecDeque::new()) +impl<'lua> MultiValue<'lua> { + pub fn new() -> MultiValue<'lua> { + MultiValue(VecDeque::new()) } } -impl<'lua> FromIterator> for LuaMultiValue<'lua> { - fn from_iter>>(iter: I) -> Self { - LuaMultiValue(VecDeque::from_iter(iter)) +impl<'lua> FromIterator> for MultiValue<'lua> { + fn from_iter>>(iter: I) -> Self { + MultiValue(VecDeque::from_iter(iter)) } } -impl<'lua> IntoIterator for LuaMultiValue<'lua> { - type Item = LuaValue<'lua>; - type IntoIter = > as IntoIterator>::IntoIter; +impl<'lua> IntoIterator for MultiValue<'lua> { + type Item = Value<'lua>; + type IntoIter = > as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } -impl<'lua> Deref for LuaMultiValue<'lua> { - type Target = VecDeque>; +impl<'lua> Deref for MultiValue<'lua> { + type Target = VecDeque>; fn deref(&self) -> &Self::Target { &self.0 } } -impl<'lua> DerefMut for LuaMultiValue<'lua> { +impl<'lua> DerefMut for MultiValue<'lua> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } @@ -106,7 +106,7 @@ impl<'lua> DerefMut for LuaMultiValue<'lua> { /// one. Any type that implements `ToLua` will automatically implement this trait. pub trait ToLuaMulti<'a> { /// Performs the conversion. - fn to_lua_multi(self, lua: &'a Lua) -> LuaResult>; + fn to_lua_multi(self, lua: &'a Lua) -> Result>; } /// Trait for types that can be created from an arbitrary number of Lua values. @@ -120,11 +120,11 @@ pub trait FromLuaMulti<'a>: Sized { /// values should be ignored. This reflects the semantics of Lua when calling a function or /// assigning values. Similarly, if not enough values are given, conversions should assume that /// any missing values are nil. - fn from_lua_multi(values: LuaMultiValue<'a>, lua: &'a Lua) -> LuaResult; + fn from_lua_multi(values: MultiValue<'a>, lua: &'a Lua) -> Result; } type LuaCallback<'lua> = Box< - FnMut(&'lua Lua, LuaMultiValue<'lua>) -> LuaResult> + FnMut(&'lua Lua, MultiValue<'lua>) -> Result> + 'lua, >; @@ -157,13 +157,13 @@ impl<'lua> Drop for LuaRef<'lua> { } /// Type of Lua integer numbers. -pub type LuaInteger = ffi::lua_Integer; +pub type Integer = ffi::lua_Integer; /// Type of Lua floating point numbers. -pub type LuaNumber = ffi::lua_Number; +pub type Number = ffi::lua_Number; /// A "light" userdata value. Equivalent to an unmanaged raw pointer. #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub struct LuaLightUserData(pub *mut c_void); +pub struct LightUserData(pub *mut c_void); /// Handle to an internal Lua string. /// @@ -190,7 +190,7 @@ impl<'lua> LuaString<'lua> { /// assert!(non_utf8.to_str().is_err()); /// # } /// ``` - pub fn to_str(&self) -> LuaResult<&str> { + pub fn to_str(&self) -> Result<&str> { let lua = self.0.lua; unsafe { stack_err_guard(lua.state, 0, || { @@ -199,7 +199,7 @@ impl<'lua> LuaString<'lua> { assert_eq!(ffi::lua_type(lua.state, -1), ffi::LUA_TSTRING); let s = CStr::from_ptr(ffi::lua_tostring(lua.state, -1)) .to_str() - .map_err(|e| LuaError::FromLuaConversionError(e.to_string()))?; + .map_err(|e| Error::FromLuaConversionError(e.to_string()))?; ffi::lua_pop(lua.state, 1); Ok(s) }) @@ -209,16 +209,16 @@ impl<'lua> LuaString<'lua> { /// Handle to an internal Lua table. #[derive(Clone, Debug)] -pub struct LuaTable<'lua>(LuaRef<'lua>); +pub struct Table<'lua>(LuaRef<'lua>); -impl<'lua> LuaTable<'lua> { +impl<'lua> Table<'lua> { /// Sets a key-value pair in the table. /// /// If the value is `nil`, this will effectively remove the pair. /// /// This might invoke the `__newindex` metamethod. Use the `raw_set` method if that is not /// desired. - pub fn set, V: ToLua<'lua>>(&self, key: K, value: V) -> LuaResult<()> { + pub fn set, V: ToLua<'lua>>(&self, key: K, value: V) -> Result<()> { let lua = self.0.lua; let key = key.to_lua(lua)?; let value = value.to_lua(lua)?; @@ -241,7 +241,7 @@ impl<'lua> LuaTable<'lua> { /// If no value is associated to `key`, returns the `nil` value. /// /// This might invoke the `__index` metamethod. Use the `raw_get` method if that is not desired. - pub fn get, V: FromLua<'lua>>(&self, key: K) -> LuaResult { + pub fn get, V: FromLua<'lua>>(&self, key: K) -> Result { let lua = self.0.lua; let key = key.to_lua(lua)?; unsafe { @@ -259,7 +259,7 @@ impl<'lua> LuaTable<'lua> { } /// Checks whether the table contains a non-nil value for `key`. - pub fn contains_key>(&self, key: K) -> LuaResult { + pub fn contains_key>(&self, key: K) -> Result { let lua = self.0.lua; let key = key.to_lua(lua)?; unsafe { @@ -277,7 +277,7 @@ impl<'lua> LuaTable<'lua> { } /// Sets a key-value pair without invoking metamethods. - pub fn raw_set, V: ToLua<'lua>>(&self, key: K, value: V) -> LuaResult<()> { + pub fn raw_set, V: ToLua<'lua>>(&self, key: K, value: V) -> Result<()> { let lua = self.0.lua; unsafe { stack_err_guard(lua.state, 0, || { @@ -293,7 +293,7 @@ impl<'lua> LuaTable<'lua> { } /// Gets the value associated to `key` without invoking metamethods. - pub fn raw_get, V: FromLua<'lua>>(&self, key: K) -> LuaResult { + pub fn raw_get, V: FromLua<'lua>>(&self, key: K) -> Result { let lua = self.0.lua; unsafe { stack_err_guard(lua.state, 0, || { @@ -311,7 +311,7 @@ impl<'lua> LuaTable<'lua> { /// Returns the result of the Lua `#` operator. /// /// This might invoke the `__len` metamethod. Use the `raw_len` method if that is not desired. - pub fn len(&self) -> LuaResult { + pub fn len(&self) -> Result { let lua = self.0.lua; unsafe { check_stack(lua.state, 3); @@ -325,7 +325,7 @@ impl<'lua> LuaTable<'lua> { } /// Returns the result of the Lua `#` operator, without invoking the `__len` metamethod. - pub fn raw_len(&self) -> LuaInteger { + pub fn raw_len(&self) -> Integer { let lua = self.0.lua; unsafe { stack_guard(lua.state, 0, || { @@ -333,20 +333,20 @@ impl<'lua> LuaTable<'lua> { lua.push_ref(lua.state, &self.0); let len = ffi::lua_rawlen(lua.state, -1); ffi::lua_pop(lua.state, 1); - len as LuaInteger + len as Integer }) } } /// Consume this table and return an iterator over the pairs of the table, works like the Lua /// 'pairs' function. - pub fn pairs, V: FromLua<'lua>>(self) -> LuaTablePairs<'lua, K, V> { + pub fn pairs, V: FromLua<'lua>>(self) -> TablePairs<'lua, K, V> { let next_key = Some(LuaRef { lua: self.0.lua, registry_id: ffi::LUA_REFNIL, }); - LuaTablePairs { + TablePairs { table: self.0, next_key, _phantom: PhantomData, @@ -356,8 +356,8 @@ impl<'lua> LuaTable<'lua> { /// Consume this table and return an iterator over the values of this table, which should be a /// sequence. Works like the Lua 'ipairs' function, but doesn't return the indexes, only the /// values in order. - pub fn sequence_values>(self) -> LuaTableSequence<'lua, V> { - LuaTableSequence { + pub fn sequence_values>(self) -> TableSequence<'lua, V> { + TableSequence { table: self.0, index: Some(1), _phantom: PhantomData, @@ -368,18 +368,18 @@ impl<'lua> LuaTable<'lua> { /// An iterator over the pairs of a Lua table. /// /// Should behave exactly like the lua 'pairs' function. Holds an internal reference to the table. -pub struct LuaTablePairs<'lua, K, V> { +pub struct TablePairs<'lua, K, V> { table: LuaRef<'lua>, next_key: Option>, _phantom: PhantomData<(K, V)>, } -impl<'lua, K, V> Iterator for LuaTablePairs<'lua, K, V> +impl<'lua, K, V> Iterator for TablePairs<'lua, K, V> where K: FromLua<'lua>, V: FromLua<'lua>, { - type Item = LuaResult<(K, V)>; + type Item = Result<(K, V)>; fn next(&mut self) -> Option { if let Some(next_key) = self.next_key.take() { @@ -422,17 +422,17 @@ where /// /// Should behave similarly to the lua 'ipairs" function, except only produces the values, not the /// indexes. Holds an internal reference to the table. -pub struct LuaTableSequence<'lua, V> { +pub struct TableSequence<'lua, V> { table: LuaRef<'lua>, - index: Option, + index: Option, _phantom: PhantomData, } -impl<'lua, V> Iterator for LuaTableSequence<'lua, V> +impl<'lua, V> Iterator for TableSequence<'lua, V> where V: FromLua<'lua>, { - type Item = LuaResult; + type Item = Result; fn next(&mut self) -> Option { if let Some(index) = self.index.take() { @@ -464,13 +464,13 @@ where /// Handle to an internal Lua function. #[derive(Clone, Debug)] -pub struct LuaFunction<'lua>(LuaRef<'lua>); +pub struct Function<'lua>(LuaRef<'lua>); -impl<'lua> LuaFunction<'lua> { +impl<'lua> Function<'lua> { /// Calls the function, passing `args` as function arguments. /// /// The function's return values are converted to the generic type `R`. - pub fn call, R: FromLuaMulti<'lua>>(&self, args: A) -> LuaResult { + pub fn call, R: FromLuaMulti<'lua>>(&self, args: A) -> Result { let lua = self.0.lua; unsafe { stack_err_guard(lua.state, 0, || { @@ -488,7 +488,7 @@ impl<'lua> LuaFunction<'lua> { pcall_with_traceback(lua.state, nargs, ffi::LUA_MULTRET), )?; let nresults = ffi::lua_gettop(lua.state) - stack_start; - let mut results = LuaMultiValue::new(); + let mut results = MultiValue::new(); for _ in 0..nresults { results.push_front(lua.pop_value(lua.state)); } @@ -519,15 +519,15 @@ impl<'lua> LuaFunction<'lua> { /// let globals = lua.globals(); /// /// // Bind the argument `123` to Lua's `tostring` function - /// let tostring: LuaFunction = globals.get("tostring").unwrap(); - /// let tostring_123: LuaFunction = tostring.bind(123i32).unwrap(); + /// let tostring: Function = globals.get("tostring").unwrap(); + /// let tostring_123: Function = tostring.bind(123i32).unwrap(); /// /// // Now we can call `tostring_123` without arguments to get the result of `tostring(123)` /// let result: String = tostring_123.call(()).unwrap(); /// assert_eq!(result, "123"); /// # } /// ``` - pub fn bind>(&self, args: A) -> LuaResult> { + pub fn bind>(&self, args: A) -> Result> { unsafe extern "C" fn bind_call_impl(state: *mut ffi::lua_State) -> c_int { let nargs = ffi::lua_gettop(state); @@ -562,7 +562,7 @@ impl<'lua> LuaFunction<'lua> { ffi::lua_pushcclosure(lua.state, bind_call_impl, nargs + 2); - Ok(LuaFunction(lua.pop_ref(lua.state))) + Ok(Function(lua.pop_ref(lua.state))) }) } } @@ -570,10 +570,10 @@ impl<'lua> LuaFunction<'lua> { /// Status of a Lua thread (or coroutine). /// -/// A `LuaThread` is `Active` before the coroutine function finishes, Dead after it finishes, and in +/// A `Thread` is `Active` before the coroutine function finishes, Dead after it finishes, and in /// Error state if error has been called inside the coroutine. #[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum LuaThreadStatus { +pub enum ThreadStatus { /// The thread has finished executing. Dead, /// The thread is currently running or suspended because it has called `coroutine.yield`. @@ -584,9 +584,9 @@ pub enum LuaThreadStatus { /// Handle to an internal Lua thread (or coroutine). #[derive(Clone, Debug)] -pub struct LuaThread<'lua>(LuaRef<'lua>); +pub struct Thread<'lua>(LuaRef<'lua>); -impl<'lua> LuaThread<'lua> { +impl<'lua> Thread<'lua> { /// Resumes execution of this thread. /// /// Equivalent to `coroutine.resume`. @@ -610,7 +610,7 @@ impl<'lua> LuaThread<'lua> { /// /// # fn main() { /// let lua = Lua::new(); - /// let thread: LuaThread = lua.eval(r#" + /// let thread: Thread = lua.eval(r#" /// coroutine.create(function(arg) /// assert(arg == 42) /// local yieldarg = coroutine.yield(123) @@ -624,12 +624,12 @@ impl<'lua> LuaThread<'lua> { /// /// // The coroutine has now returned, so `resume` will fail /// match thread.resume::<_, u32>(()) { - /// Err(LuaError::CoroutineInactive) => {}, + /// Err(Error::CoroutineInactive) => {}, /// unexpected => panic!("unexpected result {:?}", unexpected), /// } /// # } /// ``` - pub fn resume(&self, args: A) -> LuaResult + pub fn resume(&self, args: A) -> Result where A: ToLuaMulti<'lua>, R: FromLuaMulti<'lua>, @@ -644,7 +644,7 @@ impl<'lua> LuaThread<'lua> { let status = ffi::lua_status(thread_state); if status != ffi::LUA_YIELD && ffi::lua_gettop(thread_state) == 0 { - return Err(LuaError::CoroutineInactive); + return Err(Error::CoroutineInactive); } ffi::lua_pop(lua.state, 1); @@ -663,7 +663,7 @@ impl<'lua> LuaThread<'lua> { )?; let nresults = ffi::lua_gettop(thread_state); - let mut results = LuaMultiValue::new(); + let mut results = MultiValue::new(); for _ in 0..nresults { results.push_front(lua.pop_value(thread_state)); } @@ -673,7 +673,7 @@ impl<'lua> LuaThread<'lua> { } /// Gets the status of the thread. - pub fn status(&self) -> LuaThreadStatus { + pub fn status(&self) -> ThreadStatus { let lua = self.0.lua; unsafe { stack_guard(lua.state, 0, || { @@ -685,11 +685,11 @@ impl<'lua> LuaThread<'lua> { let status = ffi::lua_status(thread_state); if status != ffi::LUA_OK && status != ffi::LUA_YIELD { - LuaThreadStatus::Error + ThreadStatus::Error } else if status == ffi::LUA_YIELD || ffi::lua_gettop(thread_state) > 0 { - LuaThreadStatus::Active + ThreadStatus::Active } else { - LuaThreadStatus::Dead + ThreadStatus::Dead } }) } @@ -698,7 +698,7 @@ impl<'lua> LuaThread<'lua> { /// Kinds of metamethods that can be overridden. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] -pub enum LuaMetaMethod { +pub enum MetaMethod { /// The `+` operator. Add, /// The `-` operator. @@ -753,17 +753,17 @@ pub enum LuaMetaMethod { /// can be called as `userdata:method(args)` as expected. If there are any regular methods, and an /// `Index` metamethod is given, it will be called as a *fallback* if the index doesn't match an /// existing regular method. -pub struct LuaUserDataMethods<'lua, T> { +pub struct UserDataMethods<'lua, T> { methods: HashMap>, - meta_methods: HashMap>, + meta_methods: HashMap>, _type: PhantomData, } -impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { +impl<'lua, T: UserData> UserDataMethods<'lua, T> { /// Add a regular method as a function which accepts a &T as the first parameter. pub fn add_method(&mut self, name: &str, method: M) where - M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, LuaMultiValue<'lua>) -> LuaResult>, + M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, MultiValue<'lua>) -> Result>, { self.methods.insert( name.to_owned(), @@ -773,8 +773,8 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { /// Add a regular method as a function which accepts a &mut T as the first parameter. pub fn add_method_mut(&mut self, name: &str, method: M) - where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, LuaMultiValue<'lua>) - -> LuaResult> + where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, MultiValue<'lua>) + -> Result> { self.methods.insert( name.to_owned(), @@ -786,7 +786,7 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { /// always be a LuaUserData of type T. pub fn add_function(&mut self, name: &str, function: F) where - F: 'lua + for<'a> FnMut(&'lua Lua, LuaMultiValue<'lua>) -> LuaResult>, + F: 'lua + for<'a> FnMut(&'lua Lua, MultiValue<'lua>) -> Result>, { self.methods.insert(name.to_owned(), Box::new(function)); } @@ -794,9 +794,9 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { /// Add a metamethod as a function which accepts a &T as the first parameter. This can cause an /// error with certain binary metamethods that can trigger if ony the right side has a /// metatable. - pub fn add_meta_method(&mut self, meta: LuaMetaMethod, method: M) + pub fn add_meta_method(&mut self, meta: MetaMethod, method: M) where - M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, LuaMultiValue<'lua>) -> LuaResult>, + M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, MultiValue<'lua>) -> Result>, { self.meta_methods.insert(meta, Self::box_method(method)); } @@ -804,9 +804,9 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { /// Add a metamethod as a function which accepts a &mut T as the first parameter. This can /// cause an error with certain binary metamethods that can trigger if ony the right side has a /// metatable. - pub fn add_meta_method_mut(&mut self, meta: LuaMetaMethod, method: M) - where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, LuaMultiValue<'lua>) - -> LuaResult> + pub fn add_meta_method_mut(&mut self, meta: MetaMethod, method: M) + where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, MultiValue<'lua>) + -> Result> { self.meta_methods.insert(meta, Self::box_method_mut(method)); } @@ -815,23 +815,23 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { /// binary operators can be triggered if either the left or right argument to the binary /// operator has a metatable, so the first argument here is not necessarily a userdata of type /// T. - pub fn add_meta_function(&mut self, meta: LuaMetaMethod, function: F) + pub fn add_meta_function(&mut self, meta: MetaMethod, function: F) where - F: 'lua + for<'a> FnMut(&'lua Lua, LuaMultiValue<'lua>) -> LuaResult>, + F: 'lua + for<'a> FnMut(&'lua Lua, MultiValue<'lua>) -> Result>, { self.meta_methods.insert(meta, Box::new(function)); } fn box_method(mut method: M) -> LuaCallback<'lua> where - M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, LuaMultiValue<'lua>) -> LuaResult>, + M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, MultiValue<'lua>) -> Result>, { Box::new(move |lua, mut args| if let Some(front) = args.pop_front() { - let userdata = LuaUserData::from_lua(front, lua)?; + let userdata = AnyUserData::from_lua(front, lua)?; let userdata = userdata.borrow::()?; method(lua, &userdata, args) } else { - Err(LuaError::FromLuaConversionError( + Err(Error::FromLuaConversionError( "No userdata supplied as first argument to method" .to_owned(), )) @@ -840,16 +840,16 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { } fn box_method_mut(mut method: M) -> LuaCallback<'lua> - where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, LuaMultiValue<'lua>) - -> LuaResult> + where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, MultiValue<'lua>) + -> Result> { Box::new(move |lua, mut args| if let Some(front) = args.pop_front() { - let userdata = LuaUserData::from_lua(front, lua)?; + let userdata = AnyUserData::from_lua(front, lua)?; let mut userdata = userdata.borrow_mut::()?; method(lua, &mut userdata, args) } else { Err( - LuaError::FromLuaConversionError( + Error::FromLuaConversionError( "No userdata supplied as first argument to method".to_owned(), ).into(), ) @@ -859,43 +859,48 @@ impl<'lua, T: LuaUserDataType> LuaUserDataMethods<'lua, T> { } /// Trait for custom userdata types. -pub trait LuaUserDataType: 'static + Sized { +pub trait UserData: 'static + Sized { /// Adds custom methods and operators specific to this userdata. - fn add_methods(_methods: &mut LuaUserDataMethods) {} + fn add_methods(_methods: &mut UserDataMethods) {} } -/// Handle to an internal Lua userdata for a type that implements `LuaUserDataType`. Internally, -/// instances are stored in a `RefCell`, to best match the mutable semantics of the Lua language. +/// Handle to an internal Lua userdata for any type that implements `UserData`. +/// +/// Similar to `std::any::Any`, this provides an interface for dynamic type checking via the `is` +/// and `borrow` methods. +/// +/// Internally, instances are stored in a `RefCell`, to best match the mutable semantics of the Lua +/// language. #[derive(Clone, Debug)] -pub struct LuaUserData<'lua>(LuaRef<'lua>); +pub struct AnyUserData<'lua>(LuaRef<'lua>); -impl<'lua> LuaUserData<'lua> { +impl<'lua> AnyUserData<'lua> { /// Checks whether `T` is the type of this userdata. - pub fn is(&self) -> bool { + pub fn is(&self) -> bool { self.inspect(|_: &RefCell| ()).is_some() } /// Borrow this userdata out of the internal RefCell that is held in lua. - pub fn borrow(&self) -> LuaResult> { + pub fn borrow(&self) -> Result> { self.inspect(|cell| { Ok( - cell.try_borrow().map_err(|_| LuaError::UserDataBorrowError)?, + cell.try_borrow().map_err(|_| Error::UserDataBorrowError)?, ) - }).ok_or(LuaError::UserDataTypeMismatch)? + }).ok_or(Error::UserDataTypeMismatch)? } /// Borrow mutably this userdata out of the internal RefCell that is held in lua. - pub fn borrow_mut(&self) -> LuaResult> { + pub fn borrow_mut(&self) -> Result> { self.inspect(|cell| { Ok(cell.try_borrow_mut().map_err( - |_| LuaError::UserDataBorrowMutError, + |_| Error::UserDataBorrowMutError, )?) - }).ok_or(LuaError::UserDataTypeMismatch)? + }).ok_or(Error::UserDataTypeMismatch)? } fn inspect<'a, T, R, F>(&'a self, func: F) -> Option where - T: LuaUserDataType, + T: UserData, F: FnOnce(&'a RefCell) -> R, { unsafe { @@ -1025,14 +1030,14 @@ impl Lua { /// results in better error traces. /// /// Equivalent to Lua's `load` function. - pub fn load(&self, source: &str, name: Option<&str>) -> LuaResult { + pub fn load(&self, source: &str, name: Option<&str>) -> Result { unsafe { stack_err_guard(self.state, 0, || { handle_error( self.state, if let Some(name) = name { let name = CString::new(name.to_owned()).map_err(|e| { - LuaError::ToLuaConversionError(e.to_string()) + Error::ToLuaConversionError(e.to_string()) })?; ffi::luaL_loadbuffer( self.state, @@ -1050,7 +1055,7 @@ impl Lua { }, )?; - Ok(LuaFunction(self.pop_ref(self.state))) + Ok(Function(self.pop_ref(self.state))) }) } } @@ -1065,7 +1070,7 @@ impl Lua { &'lua self, source: &str, name: Option<&str>, - ) -> LuaResult { + ) -> Result { self.load(source, name)?.call(()) } @@ -1077,7 +1082,7 @@ impl Lua { &'lua self, source: &str, name: Option<&str>, - ) -> LuaResult { + ) -> Result { // First, try interpreting the lua as an expression by adding // "return", then as a statement. This is the same thing the // actual lua repl does. @@ -1098,18 +1103,18 @@ impl Lua { } /// Creates and returns a new table. - pub fn create_table(&self) -> LuaTable { + pub fn create_table(&self) -> Table { unsafe { stack_guard(self.state, 0, || { check_stack(self.state, 1); ffi::lua_newtable(self.state); - LuaTable(self.pop_ref(self.state)) + Table(self.pop_ref(self.state)) }) } } /// Creates a table and fills it with values from an iterator. - pub fn create_table_from<'lua, K, V, I>(&'lua self, cont: I) -> LuaResult> + pub fn create_table_from<'lua, K, V, I>(&'lua self, cont: I) -> Result> where K: ToLua<'lua>, V: ToLua<'lua>, @@ -1125,13 +1130,13 @@ impl Lua { self.push_value(self.state, v.to_lua(self)?); ffi::lua_rawset(self.state, -3); } - Ok(LuaTable(self.pop_ref(self.state))) + Ok(Table(self.pop_ref(self.state))) }) } } /// Creates a table from an iterator of values, using `1..` as the keys. - pub fn create_sequence_from<'lua, T, I>(&'lua self, cont: I) -> LuaResult> + pub fn create_sequence_from<'lua, T, I>(&'lua self, cont: I) -> Result> where T: ToLua<'lua>, I: IntoIterator, @@ -1140,9 +1145,9 @@ impl Lua { } /// Wraps a Rust function or closure, creating a callable Lua function handle to it. - pub fn create_function<'lua, F>(&'lua self, func: F) -> LuaFunction<'lua> + pub fn create_function<'lua, F>(&'lua self, func: F) -> Function<'lua> where - F: 'lua + for<'a> FnMut(&'a Lua, LuaMultiValue<'a>) -> LuaResult>, + F: 'lua + for<'a> FnMut(&'a Lua, MultiValue<'a>) -> Result>, { self.create_callback_function(Box::new(func)) } @@ -1150,7 +1155,7 @@ impl Lua { /// Wraps a Lua function into a new thread (or coroutine). /// /// Equivalent to `coroutine.create`. - pub fn create_thread<'lua>(&'lua self, func: LuaFunction<'lua>) -> LuaThread<'lua> { + pub fn create_thread<'lua>(&'lua self, func: Function<'lua>) -> Thread<'lua> { unsafe { stack_guard(self.state, 0, move || { check_stack(self.state, 1); @@ -1158,15 +1163,15 @@ impl Lua { let thread_state = ffi::lua_newthread(self.state); self.push_ref(thread_state, &func.0); - LuaThread(self.pop_ref(self.state)) + Thread(self.pop_ref(self.state)) }) } } /// Create a Lua userdata object from a custom userdata type. - pub fn create_userdata(&self, data: T) -> LuaUserData + pub fn create_userdata(&self, data: T) -> AnyUserData where - T: LuaUserDataType, + T: UserData, { unsafe { stack_guard(self.state, 0, move || { @@ -1182,18 +1187,18 @@ impl Lua { ffi::lua_setmetatable(self.state, -2); - LuaUserData(self.pop_ref(self.state)) + AnyUserData(self.pop_ref(self.state)) }) } } /// Returns a handle to the global environment. - pub fn globals(&self) -> LuaTable { + pub fn globals(&self) -> Table { unsafe { stack_guard(self.state, 0, move || { check_stack(self.state, 1); ffi::lua_rawgeti(self.state, ffi::LUA_REGISTRYINDEX, ffi::LUA_RIDX_GLOBALS); - LuaTable(self.pop_ref(self.state)) + Table(self.pop_ref(self.state)) }) } } @@ -1201,16 +1206,16 @@ impl Lua { /// Coerces a Lua value to a string. /// /// The value must be a string (in which case this is a no-op) or a number. - pub fn coerce_string<'lua>(&'lua self, v: LuaValue<'lua>) -> LuaResult> { + pub fn coerce_string<'lua>(&'lua self, v: Value<'lua>) -> Result> { match v { - LuaValue::String(s) => Ok(s), + Value::String(s) => Ok(s), v => unsafe { stack_guard(self.state, 0, || { check_stack(self.state, 1); self.push_value(self.state, v); if ffi::lua_tostring(self.state, -1).is_null() { ffi::lua_pop(self.state, 1); - Err(LuaError::FromLuaConversionError( + Err(Error::FromLuaConversionError( "cannot convert lua value to string".to_owned(), )) } else { @@ -1225,9 +1230,9 @@ impl Lua { /// /// The value must be an integer, or a floating point number or a string that can be converted /// to an integer. Refer to the Lua manual for details. - pub fn coerce_integer(&self, v: LuaValue) -> LuaResult { + pub fn coerce_integer(&self, v: Value) -> Result { match v { - LuaValue::Integer(i) => Ok(i), + Value::Integer(i) => Ok(i), v => unsafe { stack_guard(self.state, 0, || { check_stack(self.state, 1); @@ -1236,7 +1241,7 @@ impl Lua { let i = ffi::lua_tointegerx(self.state, -1, &mut isint); ffi::lua_pop(self.state, 1); if isint == 0 { - Err(LuaError::FromLuaConversionError( + Err(Error::FromLuaConversionError( "cannot convert lua value to integer".to_owned(), )) } else { @@ -1251,9 +1256,9 @@ impl Lua { /// /// The value must be a number or a string that can be converted to a number. Refer to the Lua /// manual for details. - pub fn coerce_number(&self, v: LuaValue) -> LuaResult { + pub fn coerce_number(&self, v: Value) -> Result { match v { - LuaValue::Number(n) => Ok(n), + Value::Number(n) => Ok(n), v => unsafe { stack_guard(self.state, 0, || { check_stack(self.state, 1); @@ -1262,7 +1267,7 @@ impl Lua { let n = ffi::lua_tonumberx(self.state, -1, &mut isnum); ffi::lua_pop(self.state, 1); if isnum == 0 { - Err(LuaError::FromLuaConversionError( + Err(Error::FromLuaConversionError( "cannot convert lua value to number".to_owned(), )) } else { @@ -1273,32 +1278,32 @@ impl Lua { } } - pub fn from<'lua, T: ToLua<'lua>>(&'lua self, t: T) -> LuaResult> { + pub fn from<'lua, T: ToLua<'lua>>(&'lua self, t: T) -> Result> { t.to_lua(self) } - pub fn to<'lua, T: FromLua<'lua>>(&'lua self, value: LuaValue<'lua>) -> LuaResult { + pub fn to<'lua, T: FromLua<'lua>>(&'lua self, value: Value<'lua>) -> Result { T::from_lua(value, self) } - /// Packs up a value that implements `ToLuaMulti` into a `LuaMultiValue` instance. + /// Packs up a value that implements `ToLuaMulti` into a `MultiValue` instance. /// /// This can be used to return arbitrary Lua values from a Rust function back to Lua. - pub fn pack<'lua, T: ToLuaMulti<'lua>>(&'lua self, t: T) -> LuaResult> { + pub fn pack<'lua, T: ToLuaMulti<'lua>>(&'lua self, t: T) -> Result> { t.to_lua_multi(self) } - /// Unpacks a `LuaMultiValue` instance into a value that implements `FromLuaMulti`. + /// Unpacks a `MultiValue` instance into a value that implements `FromLuaMulti`. /// /// This can be used to convert the arguments of a Rust function called by Lua. pub fn unpack<'lua, T: FromLuaMulti<'lua>>( &'lua self, - value: LuaMultiValue<'lua>, - ) -> LuaResult { + value: MultiValue<'lua>, + ) -> Result { T::from_lua_multi(value, self) } - fn create_callback_function<'lua>(&'lua self, func: LuaCallback<'lua>) -> LuaFunction<'lua> { + fn create_callback_function<'lua>(&'lua self, func: LuaCallback<'lua>) -> Function<'lua> { unsafe extern "C" fn callback_call_impl(state: *mut ffi::lua_State) -> c_int { callback_error(state, || { let lua = Lua { @@ -1310,7 +1315,7 @@ impl Lua { let func = &mut *get_userdata::(state, ffi::lua_upvalueindex(1)); let nargs = ffi::lua_gettop(state); - let mut args = LuaMultiValue::new(); + let mut args = MultiValue::new(); for _ in 0..nargs { args.push_front(lua.pop_value(state)); } @@ -1341,60 +1346,60 @@ impl Lua { ffi::lua_pushcclosure(self.state, callback_call_impl, 1); - LuaFunction(self.pop_ref(self.state)) + Function(self.pop_ref(self.state)) }) } } - unsafe fn push_value(&self, state: *mut ffi::lua_State, value: LuaValue) { + unsafe fn push_value(&self, state: *mut ffi::lua_State, value: Value) { match value { - LuaValue::Nil => { + Value::Nil => { ffi::lua_pushnil(state); } - LuaValue::Boolean(b) => { + Value::Boolean(b) => { ffi::lua_pushboolean(state, if b { 1 } else { 0 }); } - LuaValue::LightUserData(ud) => { + Value::LightUserData(ud) => { ffi::lua_pushlightuserdata(state, ud.0); } - LuaValue::Integer(i) => { + Value::Integer(i) => { ffi::lua_pushinteger(state, i); } - LuaValue::Number(n) => { + Value::Number(n) => { ffi::lua_pushnumber(state, n); } - LuaValue::String(s) => { + Value::String(s) => { self.push_ref(state, &s.0); } - LuaValue::Table(t) => { + Value::Table(t) => { self.push_ref(state, &t.0); } - LuaValue::Function(f) => { + Value::Function(f) => { self.push_ref(state, &f.0); } - LuaValue::Thread(t) => { + Value::Thread(t) => { self.push_ref(state, &t.0); } - LuaValue::UserData(ud) => { + Value::UserData(ud) => { self.push_ref(state, &ud.0); } - LuaValue::Error(e) => { + Value::Error(e) => { push_wrapped_error(state, e); } } } - unsafe fn pop_value(&self, state: *mut ffi::lua_State) -> LuaValue { + unsafe fn pop_value(&self, state: *mut ffi::lua_State) -> Value { match ffi::lua_type(state, -1) { ffi::LUA_TNIL => { ffi::lua_pop(state, 1); @@ -1402,48 +1407,48 @@ impl Lua { } ffi::LUA_TBOOLEAN => { - let b = LuaValue::Boolean(ffi::lua_toboolean(state, -1) != 0); + let b = Value::Boolean(ffi::lua_toboolean(state, -1) != 0); ffi::lua_pop(state, 1); b } ffi::LUA_TLIGHTUSERDATA => { - let ud = LuaValue::LightUserData(LuaLightUserData(ffi::lua_touserdata(state, -1))); + let ud = Value::LightUserData(LightUserData(ffi::lua_touserdata(state, -1))); ffi::lua_pop(state, 1); ud } ffi::LUA_TNUMBER => { if ffi::lua_isinteger(state, -1) != 0 { - let i = LuaValue::Integer(ffi::lua_tointeger(state, -1)); + let i = Value::Integer(ffi::lua_tointeger(state, -1)); ffi::lua_pop(state, 1); i } else { - let n = LuaValue::Number(ffi::lua_tonumber(state, -1)); + let n = Value::Number(ffi::lua_tonumber(state, -1)); ffi::lua_pop(state, 1); n } } - ffi::LUA_TSTRING => LuaValue::String(LuaString(self.pop_ref(state))), + ffi::LUA_TSTRING => Value::String(LuaString(self.pop_ref(state))), - ffi::LUA_TTABLE => LuaValue::Table(LuaTable(self.pop_ref(state))), + ffi::LUA_TTABLE => Value::Table(Table(self.pop_ref(state))), - ffi::LUA_TFUNCTION => LuaValue::Function(LuaFunction(self.pop_ref(state))), + ffi::LUA_TFUNCTION => Value::Function(Function(self.pop_ref(state))), ffi::LUA_TUSERDATA => { // It should not be possible to interact with userdata types - // other than custom LuaUserDataType types OR a WrappedError. + // other than custom UserData types OR a WrappedError. // WrappedPanic should never be able to be caught in lua, so it // should never be here. if let Some(err) = pop_wrapped_error(state) { - LuaValue::Error(err) + Value::Error(err) } else { - LuaValue::UserData(LuaUserData(self.pop_ref(state))) + Value::UserData(AnyUserData(self.pop_ref(state))) } } - ffi::LUA_TTHREAD => LuaValue::Thread(LuaThread(self.pop_ref(state))), + ffi::LUA_TTHREAD => Value::Thread(Thread(self.pop_ref(state))), _ => unreachable!("internal error: LUA_TNONE in pop_value"), } @@ -1453,7 +1458,7 @@ impl Lua { assert_eq!( lref.lua.main_state, self.main_state, - "Lua instance passed LuaValue created from a different Lua" + "Lua instance passed Value created from a different Lua" ); ffi::lua_rawgeti( @@ -1476,7 +1481,7 @@ impl Lua { } } - unsafe fn userdata_metatable(&self) -> c_int { + unsafe fn userdata_metatable(&self) -> c_int { // Used if both an __index metamethod is set and regular methods, checks methods table // first, then __index metamethod. unsafe extern "C" fn meta_index_impl(state: *mut ffi::lua_State) -> c_int { @@ -1512,7 +1517,7 @@ impl Lua { HashMapEntry::Vacant(entry) => { ffi::lua_newtable(self.state); - let mut methods = LuaUserDataMethods { + let mut methods = UserDataMethods { methods: HashMap::new(), meta_methods: HashMap::new(), _type: PhantomData, @@ -1529,7 +1534,7 @@ impl Lua { push_string(self.state, &k); self.push_value( self.state, - LuaValue::Function(self.create_callback_function(m)), + Value::Function(self.create_callback_function(m)), ); ffi::lua_rawset(self.state, -3); } @@ -1538,46 +1543,46 @@ impl Lua { } for (k, m) in methods.meta_methods { - if k == LuaMetaMethod::Index && has_methods { + if k == MetaMethod::Index && has_methods { push_string(self.state, "__index"); ffi::lua_pushvalue(self.state, -1); ffi::lua_gettable(self.state, -3); self.push_value( self.state, - LuaValue::Function(self.create_callback_function(m)), + Value::Function(self.create_callback_function(m)), ); ffi::lua_pushcclosure(self.state, meta_index_impl, 2); ffi::lua_rawset(self.state, -3); } else { let name = match k { - LuaMetaMethod::Add => "__add", - LuaMetaMethod::Sub => "__sub", - LuaMetaMethod::Mul => "__mul", - LuaMetaMethod::Div => "__div", - LuaMetaMethod::Mod => "__mod", - LuaMetaMethod::Pow => "__pow", - LuaMetaMethod::Unm => "__unm", - LuaMetaMethod::IDiv => "__idiv", - LuaMetaMethod::BAnd => "__band", - LuaMetaMethod::BOr => "__bor", - LuaMetaMethod::BXor => "__bxor", - LuaMetaMethod::BNot => "__bnot", - LuaMetaMethod::Shl => "__shl", - LuaMetaMethod::Shr => "__shr", - LuaMetaMethod::Concat => "__concat", - LuaMetaMethod::Len => "__len", - LuaMetaMethod::Eq => "__eq", - LuaMetaMethod::Lt => "__lt", - LuaMetaMethod::Le => "__le", - LuaMetaMethod::Index => "__index", - LuaMetaMethod::NewIndex => "__newIndex", - LuaMetaMethod::Call => "__call", - LuaMetaMethod::ToString => "__tostring", + MetaMethod::Add => "__add", + MetaMethod::Sub => "__sub", + MetaMethod::Mul => "__mul", + MetaMethod::Div => "__div", + MetaMethod::Mod => "__mod", + MetaMethod::Pow => "__pow", + MetaMethod::Unm => "__unm", + MetaMethod::IDiv => "__idiv", + MetaMethod::BAnd => "__band", + MetaMethod::BOr => "__bor", + MetaMethod::BXor => "__bxor", + MetaMethod::BNot => "__bnot", + MetaMethod::Shl => "__shl", + MetaMethod::Shr => "__shr", + MetaMethod::Concat => "__concat", + MetaMethod::Len => "__len", + MetaMethod::Eq => "__eq", + MetaMethod::Lt => "__lt", + MetaMethod::Le => "__le", + MetaMethod::Index => "__index", + MetaMethod::NewIndex => "__newIndex", + MetaMethod::Call => "__call", + MetaMethod::ToString => "__tostring", }; push_string(self.state, name); self.push_value( self.state, - LuaValue::Function(self.create_callback_function(m)), + Value::Function(self.create_callback_function(m)), ); ffi::lua_rawset(self.state, -3); } diff --git a/src/multi.rs b/src/multi.rs index 4fc804d..046137f 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -4,22 +4,22 @@ use error::*; use lua::*; impl<'lua> ToLuaMulti<'lua> for () { - fn to_lua_multi(self, _: &'lua Lua) -> LuaResult { - Ok(LuaMultiValue::new()) + fn to_lua_multi(self, _: &'lua Lua) -> Result { + Ok(MultiValue::new()) } } impl<'lua> FromLuaMulti<'lua> for () { - fn from_lua_multi(_: LuaMultiValue, _: &'lua Lua) -> LuaResult { + fn from_lua_multi(_: MultiValue, _: &'lua Lua) -> Result { 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 { - fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult> { - let mut result = LuaMultiValue::new(); +impl<'lua, T: ToLua<'lua>, E: ToLua<'lua>> ToLuaMulti<'lua> for ::std::result::Result { + fn to_lua_multi(self, lua: &'lua Lua) -> Result> { + 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 { } impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for T { - fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult> { - let mut v = LuaMultiValue::new(); + fn to_lua_multi(self, lua: &'lua Lua) -> Result> { + 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 { + fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result { 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> { +impl<'lua> ToLuaMulti<'lua> for MultiValue<'lua> { + fn to_lua_multi(self, _: &'lua Lua) -> Result> { Ok(self) } } -impl<'lua> FromLuaMulti<'lua> for LuaMultiValue<'lua> { - fn from_lua_multi(values: LuaMultiValue<'lua>, _: &'lua Lua) -> LuaResult { +impl<'lua> FromLuaMulti<'lua> for MultiValue<'lua> { + fn from_lua_multi(values: MultiValue<'lua>, _: &'lua Lua) -> Result { 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(pub Vec); +pub struct Variadic(pub Vec); -impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for LuaVariadic { - fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult> { +impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for Variadic { + fn to_lua_multi(self, lua: &'lua Lua) -> Result> { self.0.into_iter().map(|e| e.to_lua(lua)).collect() } } -impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for LuaVariadic { - fn from_lua_multi(values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult { +impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for Variadic { + fn from_lua_multi(values: MultiValue<'lua>, lua: &'lua Lua) -> Result { values .into_iter() .map(|e| T::from_lua(e, lua)) - .collect::>>() - .map(LuaVariadic) + .collect::>>() + .map(Variadic) } } impl<'lua> ToLuaMulti<'lua> for HNil { - fn to_lua_multi(self, _: &'lua Lua) -> LuaResult> { - Ok(LuaMultiValue::new()) + fn to_lua_multi(self, _: &'lua Lua) -> Result> { + Ok(MultiValue::new()) } } impl<'lua> FromLuaMulti<'lua> for HNil { - fn from_lua_multi(_: LuaMultiValue<'lua>, _: &'lua Lua) -> LuaResult { + fn from_lua_multi(_: MultiValue<'lua>, _: &'lua Lua) -> Result { Ok(HNil) } } impl<'lua, T: ToLuaMulti<'lua>> ToLuaMulti<'lua> for HCons { - fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult> { + fn to_lua_multi(self, lua: &'lua Lua) -> Result> { self.0.to_lua_multi(lua) } } impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for HCons { - fn from_lua_multi(values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult { + fn from_lua_multi(values: MultiValue<'lua>, lua: &'lua Lua) -> Result { Ok(HCons(T::from_lua_multi(values, lua)?, HNil)) } } @@ -108,7 +108,7 @@ impl<'lua, T: FromLuaMulti<'lua>> FromLuaMulti<'lua> for HCons { impl<'lua, H: ToLua<'lua>, A, B> ToLuaMulti<'lua> for HCons> where HCons: ToLuaMulti<'lua> { - fn to_lua_multi(self, lua: &'lua Lua) -> LuaResult> { + fn to_lua_multi(self, lua: &'lua Lua) -> Result> { 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> impl<'lua, H: FromLua<'lua>, A, B> FromLuaMulti<'lua> for HCons> where HCons: FromLuaMulti<'lua> { - fn from_lua_multi(mut values: LuaMultiValue<'lua>, lua: &'lua Lua) -> LuaResult { + fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result { let val = H::from_lua(values.pop_front().unwrap_or(LuaNil), lua)?; let res = HCons::::from_lua_multi(values, lua)?; Ok(HCons(val, res)) diff --git a/src/tests.rs b/src/tests.rs index e7d7d1e..a4bd5dc 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -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::("false == false", None).unwrap(), true); assert_eq!(lua.eval::("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::>>() + .collect::>>() .unwrap(), vec![(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)] ); @@ -114,7 +113,7 @@ fn test_table() { table1 .clone() .sequence_values() - .collect::>>() + .collect::>>() .unwrap(), vec![1, 2, 3, 4, 5] ); @@ -124,14 +123,14 @@ fn test_table() { table2 .clone() .pairs() - .collect::>>() + .collect::>>() .unwrap(), vec![] ); assert_eq!( table2 .sequence_values() - .collect::>>() + .collect::>>() .unwrap(), vec![] ); @@ -140,7 +139,7 @@ fn test_table() { assert_eq!( table3 .sequence_values() - .collect::>>() + .collect::>>() .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::>>() + .collect::>>() .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); - 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) { + impl UserData for MyUserData { + fn add_methods(methods: &mut UserDataMethods) { 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::().unwrap().0 = 64; + userdata.borrow_mut::().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) { + impl UserData for MyUserData { + fn add_methods(methods: &mut UserDataMethods) { 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::(args)?; - lua.pack(UserData(lhs.0 + rhs.0)) + methods.add_meta_function(MetaMethod::Add, |lua, args| { + let hlist_pat![lhs, rhs] = lua.unpack::(args)?; + lua.pack(MyUserData(lhs.0 + rhs.0)) }); - methods.add_meta_function(LuaMetaMethod::Sub, |lua, args| { - let hlist_pat![lhs, rhs] = lua.unpack::(args)?; - lua.pack(UserData(lhs.0 - rhs.0)) + methods.add_meta_function(MetaMethod::Sub, |lua, args| { + let hlist_pat![lhs, rhs] = lua.unpack::(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::(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::("userdata1 + userdata2", None) + lua.eval::("userdata1 + userdata2", None) .unwrap() .0, 10 ); assert_eq!( - lua.eval::("userdata1 - userdata2", None) + lua.eval::("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::(); @@ -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]>(hlist![]).unwrap(); + let hlist_pat![a, b, Variadic(v)] = + mreturn.call::<_, HList![u64, u64, Variadic]>(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::( + lua.eval::( 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::( + lua.eval::( 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::( + let thread = lua.eval::( 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::( + lua.pack(Err::( "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(); diff --git a/src/util.rs b/src/util.rs index 8fdba9a..70e9e15 100644 --- a/src/util.rs +++ b/src/util.rs @@ -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( state: *mut ffi::lua_State, change: c_int, op: F, -) -> LuaResult +) -> Result where - F: FnOnce() -> LuaResult, + F: FnOnce() -> Result, { let expected = ffi::lua_gettop(state) + change; lua_assert!( @@ -161,9 +161,9 @@ pub unsafe fn error_guard( state: *mut ffi::lua_State, nargs: c_int, func: F, -) -> LuaResult +) -> Result where - F: FnOnce(*mut ffi::lua_State) -> LuaResult + UnwindSafe, + F: FnOnce(*mut ffi::lua_State) -> Result + UnwindSafe, { unsafe extern "C" fn call_impl(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("") { - 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(state: *mut ffi::lua_State) -> c // the rust side, it will resume the panic. pub unsafe fn callback_error(state: *mut ffi::lua_State, f: F) -> R where - F: FnOnce() -> LuaResult + UnwindSafe, + F: FnOnce() -> Result + 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(|_| "") .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(|_| "") .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>); // 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::(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 Option { +pub unsafe fn pop_wrapped_error(state: *mut ffi::lua_State) -> Option { if ffi::lua_gettop(state) == 0 || !is_wrapped_error(state, -1) { None } else { From 8bd0c2c812035f2bb95627d26a98ee9c2fbeb19d Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Thu, 20 Jul 2017 11:33:15 +0200 Subject: [PATCH 2/6] Rename `LuaString` to `String` This required a lot of little adjustments where we used std's `String` before. In downstream code, this shouldn't be necessary, as you can just do `use rlua::String as LuaString` to disambiguate. --- examples/examples.rs | 2 +- examples/repl.rs | 2 +- src/conversion.rs | 11 ++++++----- src/lua.rs | 27 ++++++++++++++------------- src/tests.rs | 6 +++++- 5 files changed, 27 insertions(+), 21 deletions(-) diff --git a/examples/examples.rs b/examples/examples.rs index 5ee0758..15e034d 100644 --- a/examples/examples.rs +++ b/examples/examples.rs @@ -4,7 +4,7 @@ extern crate rlua; use std::f32; -use rlua::*; +use rlua::{Lua, Result, Function, Variadic, UserData, UserDataMethods, MetaMethod}; fn examples() -> Result<()> { // Create a Lua context with Lua::new(). Eventually, this will allow diff --git a/examples/repl.rs b/examples/repl.rs index 0d6bf9c..27ef0f9 100644 --- a/examples/repl.rs +++ b/examples/repl.rs @@ -2,7 +2,7 @@ extern crate rlua; -use rlua::*; +use rlua::{Lua, MultiValue, Error}; use std::io::prelude::*; use std::io::{stdin, stdout, stderr, BufReader}; diff --git a/src/conversion.rs b/src/conversion.rs index df1ccad..1b0a0bc 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -1,5 +1,6 @@ use std::collections::{HashMap, BTreeMap}; use std::hash::Hash; +use std::string::String as StdString; use error::*; use lua::*; @@ -16,14 +17,14 @@ impl<'lua> FromLua<'lua> for Value<'lua> { } } -impl<'lua> ToLua<'lua> for LuaString<'lua> { +impl<'lua> ToLua<'lua> for String<'lua> { fn to_lua(self, _: &'lua Lua) -> Result> { Ok(Value::String(self)) } } -impl<'lua> FromLua<'lua> for LuaString<'lua> { - fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result> { +impl<'lua> FromLua<'lua> for String<'lua> { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result> { lua.coerce_string(value) } } @@ -165,13 +166,13 @@ impl<'lua> FromLua<'lua> for LightUserData { } } -impl<'lua> ToLua<'lua> for String { +impl<'lua> ToLua<'lua> for StdString { fn to_lua(self, lua: &'lua Lua) -> Result> { Ok(Value::String(lua.create_string(&self))) } } -impl<'lua> FromLua<'lua> for String { +impl<'lua> FromLua<'lua> for StdString { fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { Ok(lua.coerce_string(value)?.to_str()?.to_owned()) } diff --git a/src/lua.rs b/src/lua.rs index 8290e0d..3344018 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -9,6 +9,7 @@ use std::marker::PhantomData; use std::collections::{HashMap, VecDeque}; use std::collections::hash_map::Entry as HashMapEntry; use std::os::raw::{c_char, c_int, c_void}; +use std::string::String as StdString; use ffi; use error::*; @@ -32,7 +33,7 @@ pub enum Value<'lua> { /// An interned string, managed by Lua. /// /// Unlike Rust strings, Lua strings may not be valid UTF-8. - String(LuaString<'lua>), + String(String<'lua>), /// Reference to a Lua table. Table(Table<'lua>), /// Reference to a Lua function (or closure). @@ -169,24 +170,24 @@ pub struct LightUserData(pub *mut c_void); /// /// Unlike Rust strings, Lua strings may not be valid UTF-8. #[derive(Clone, Debug)] -pub struct LuaString<'lua>(LuaRef<'lua>); +pub struct String<'lua>(LuaRef<'lua>); -impl<'lua> LuaString<'lua> { +impl<'lua> String<'lua> { /// Get a `&str` slice if the Lua string is valid UTF-8. /// /// # Example /// /// ``` /// # extern crate rlua; - /// # use rlua::*; + /// # use rlua::{Lua, String}; /// # fn main() { /// let lua = Lua::new(); /// let globals = lua.globals(); /// - /// let version: LuaString = globals.get("_VERSION").unwrap(); + /// let version: String = globals.get("_VERSION").unwrap(); /// assert!(version.to_str().unwrap().contains("Lua")); /// - /// let non_utf8: LuaString = lua.eval(r#" "test\xff" "#, None).unwrap(); + /// let non_utf8: String = lua.eval(r#" "test\xff" "#, None).unwrap(); /// assert!(non_utf8.to_str().is_err()); /// # } /// ``` @@ -512,7 +513,7 @@ impl<'lua> Function<'lua> { /// /// ``` /// # extern crate rlua; - /// # use rlua::*; + /// # use rlua::{Lua, Function}; /// /// # fn main() { /// let lua = Lua::new(); @@ -754,7 +755,7 @@ pub enum MetaMethod { /// `Index` metamethod is given, it will be called as a *fallback* if the index doesn't match an /// existing regular method. pub struct UserDataMethods<'lua, T> { - methods: HashMap>, + methods: HashMap>, meta_methods: HashMap>, _type: PhantomData, } @@ -1092,12 +1093,12 @@ impl Lua { } /// Pass a `&str` slice to Lua, creating and returning a interned Lua string. - pub fn create_string(&self, s: &str) -> LuaString { + pub fn create_string(&self, s: &str) -> String { unsafe { stack_guard(self.state, 0, || { check_stack(self.state, 1); ffi::lua_pushlstring(self.state, s.as_ptr() as *const c_char, s.len()); - LuaString(self.pop_ref(self.state)) + String(self.pop_ref(self.state)) }) } } @@ -1206,7 +1207,7 @@ impl Lua { /// Coerces a Lua value to a string. /// /// The value must be a string (in which case this is a no-op) or a number. - pub fn coerce_string<'lua>(&'lua self, v: Value<'lua>) -> Result> { + pub fn coerce_string<'lua>(&'lua self, v: Value<'lua>) -> Result> { match v { Value::String(s) => Ok(s), v => unsafe { @@ -1219,7 +1220,7 @@ impl Lua { "cannot convert lua value to string".to_owned(), )) } else { - Ok(LuaString(self.pop_ref(self.state))) + Ok(String(self.pop_ref(self.state))) } }) }, @@ -1430,7 +1431,7 @@ impl Lua { } } - ffi::LUA_TSTRING => Value::String(LuaString(self.pop_ref(state))), + ffi::LUA_TSTRING => Value::String(String(self.pop_ref(state))), ffi::LUA_TTABLE => Value::Table(Table(self.pop_ref(state))), diff --git a/src/tests.rs b/src/tests.rs index a4bd5dc..e5e733d 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -3,7 +3,11 @@ use std::error; use std::panic::catch_unwind; use std::os::raw::c_void; -use super::*; +use String as LuaString; +use { + Lua, Result, LuaExternalError, LightUserData, UserDataMethods, UserData, Table, Thread, + ThreadStatus, Error, Function, Value, Variadic, MetaMethod +}; #[test] fn test_set_get() { From b47f9e0d764ba843e1f0ac4edd2d17bd63f81a18 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Sun, 23 Jul 2017 12:29:02 +0200 Subject: [PATCH 3/6] Continue renames in comments/strings --- src/error.rs | 6 +++--- src/lua.rs | 4 ++-- src/tests.rs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/error.rs b/src/error.rs index 835d086..6e81b22 100644 --- a/src/error.rs +++ b/src/error.rs @@ -18,11 +18,11 @@ pub enum Error { FromLuaConversionError(String), /// A `Thread` was resumed and the coroutine was no longer active. CoroutineInactive, - /// A `LuaUserData` is not the expected type in a borrow. + /// An `AnyUserData` is not the expected type in a borrow. UserDataTypeMismatch, - /// A `LuaUserData` immutable borrow failed because it is already borrowed mutably. + /// An `AnyUserData` immutable borrow failed because it is already borrowed mutably. UserDataBorrowError, - /// A `LuaUserData` mutable borrow failed because it is already borrowed. + /// An `AnyUserData` mutable borrow failed because it is already borrowed. UserDataBorrowMutError, /// 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. diff --git a/src/lua.rs b/src/lua.rs index 3344018..7559ef7 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -784,7 +784,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> { } /// Add a regular method as a function which accepts generic arguments, the first argument will - /// always be a LuaUserData of type T. + /// always be a `UserData` of type T. pub fn add_function(&mut self, name: &str, function: F) where F: 'lua + for<'a> FnMut(&'lua Lua, MultiValue<'lua>) -> Result>, @@ -914,7 +914,7 @@ impl<'lua> AnyUserData<'lua> { lua_assert!( lua.state, ffi::lua_getmetatable(lua.state, -1) != 0, - "LuaUserData missing metatable" + "AnyUserData missing metatable" ); ffi::lua_rawgeti( diff --git a/src/tests.rs b/src/tests.rs index e5e733d..d6a6c81 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -381,7 +381,7 @@ fn test_scope() { // { // let touter = globals.get::<_, Table>("touter").unwrap(); // touter.set("userdata", lua.create_userdata(UserData).unwrap()).unwrap(); - // let userdata = touter.get::<_, LuaUserData>("userdata").unwrap(); + // let userdata = touter.get::<_, AnyUserData>("userdata").unwrap(); // userdata_ref = userdata.borrow::(); // } } From 8f044755dcdc91837a3d53e7ec25b95c9d836b20 Mon Sep 17 00:00:00 2001 From: Jonas Schievink Date: Sun, 23 Jul 2017 18:37:48 +0200 Subject: [PATCH 4/6] Fixes after rebase --- src/tests.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/tests.rs b/src/tests.rs index d6a6c81..4b81908 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -809,12 +809,12 @@ fn test_num_conversion() { #[test] #[should_panic] fn test_expired_userdata() { - struct Userdata { + struct MyUserdata { id: u8, } - impl LuaUserDataType for Userdata { - fn add_methods(methods: &mut LuaUserDataMethods) { + impl UserData for MyUserdata { + fn add_methods(methods: &mut UserDataMethods) { methods.add_method("access", |lua, this, _| { assert!(this.id == 123); lua.pack(()) @@ -825,7 +825,7 @@ fn test_expired_userdata() { let lua = Lua::new(); { let globals = lua.globals(); - globals.set("userdata", Userdata { id: 123 }).unwrap(); + globals.set("userdata", MyUserdata { id: 123 }).unwrap(); } lua.eval::<()>(r#" @@ -849,11 +849,11 @@ fn detroys_userdata() { static DROPPED: AtomicBool = ATOMIC_BOOL_INIT; - struct Userdata; + struct MyUserdata; - impl LuaUserDataType for Userdata {} + impl UserData for MyUserdata {} - impl Drop for Userdata { + impl Drop for MyUserdata { fn drop(&mut self) { DROPPED.store(true, Ordering::SeqCst); } @@ -862,7 +862,7 @@ fn detroys_userdata() { let lua = Lua::new(); { let globals = lua.globals(); - globals.set("userdata", Userdata).unwrap(); + globals.set("userdata", MyUserdata).unwrap(); } assert_eq!(DROPPED.load(Ordering::SeqCst), false); From c7d2311c6a00d686113a35a4f7692704f39182f8 Mon Sep 17 00:00:00 2001 From: kyren Date: Mon, 24 Jul 2017 07:12:52 -0400 Subject: [PATCH 5/6] Do several more Lua prefix renames, add prelude module Rename the following: LuaNil => Nil LuaExternalError => ExternalError LuaExternalResult => ExternalResult LuaCallback => Callback (internal only) Use qualified re-exports at the top of the module. Add a new public 'prelude' module which re-exports everything with a non-conflicting name (Adds back the Lua prefix), and is meant to be imported unqualified. --- src/conversion.rs | 4 ++-- src/error.rs | 10 +++++----- src/lib.rs | 10 +++++++--- src/lua.rs | 25 +++++++++++-------------- src/multi.rs | 6 +++--- src/prelude.rs | 8 ++++++++ src/tests.rs | 2 +- 7 files changed, 37 insertions(+), 28 deletions(-) create mode 100644 src/prelude.rs diff --git a/src/conversion.rs b/src/conversion.rs index 1b0a0bc..6fac7e6 100644 --- a/src/conversion.rs +++ b/src/conversion.rs @@ -288,7 +288,7 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option { fn to_lua(self, lua: &'lua Lua) -> Result> { match self { Some(val) => val.to_lua(lua), - None => Ok(LuaNil), + None => Ok(Nil), } } } @@ -296,7 +296,7 @@ impl<'lua, T: ToLua<'lua>> ToLua<'lua> for Option { impl<'lua, T: FromLua<'lua>> FromLua<'lua> for Option { fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> Result { match value { - LuaNil => Ok(None), + Nil => Ok(None), value => Ok(Some(T::from_lua(value, lua)?)), } } diff --git a/src/error.rs b/src/error.rs index 6e81b22..a11d84b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -94,11 +94,11 @@ impl Error { } } -pub trait LuaExternalError { +pub trait ExternalError { fn to_lua_err(self) -> Error; } -impl LuaExternalError for E +impl ExternalError for E where E: Into>, { @@ -122,13 +122,13 @@ where } } -pub trait LuaExternalResult { +pub trait ExternalResult { fn to_lua_err(self) -> Result; } -impl LuaExternalResult for ::std::result::Result +impl ExternalResult for ::std::result::Result where - E: LuaExternalError, + E: ExternalError, { fn to_lua_err(self) -> Result { self.map_err(|e| e.to_lua_err()) diff --git a/src/lib.rs b/src/lib.rs index ee25344..2a36825 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,10 @@ mod multi; #[cfg(test)] mod tests; -pub use error::*; -pub use lua::*; -pub use multi::*; +pub use error::{Error, Result, ExternalError, ExternalResult}; +pub use lua::{Value, Nil, ToLua, FromLua, MultiValue, ToLuaMulti, FromLuaMulti, Integer, Number, + LightUserData, String, Table, TablePairs, TableSequence, Function, ThreadStatus, + Thread, MetaMethod, UserDataMethods, UserData, AnyUserData, Lua}; +pub use multi::Variadic; + +pub mod prelude; diff --git a/src/lua.rs b/src/lua.rs index 7559ef7..f97eae5 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -48,7 +48,7 @@ pub enum Value<'lua> { /// it is implicitly cloned. Error(Error), } -pub use self::Value::Nil as LuaNil; +pub use self::Value::Nil as Nil; /// Trait for types convertible to `Value`. pub trait ToLua<'a> { @@ -124,10 +124,7 @@ pub trait FromLuaMulti<'a>: Sized { fn from_lua_multi(values: MultiValue<'a>, lua: &'a Lua) -> Result; } -type LuaCallback<'lua> = Box< - FnMut(&'lua Lua, MultiValue<'lua>) -> Result> - + 'lua, ->; +type Callback<'lua> = Box) -> Result> + 'lua>; struct LuaRef<'lua> { lua: &'lua Lua, @@ -755,8 +752,8 @@ pub enum MetaMethod { /// `Index` metamethod is given, it will be called as a *fallback* if the index doesn't match an /// existing regular method. pub struct UserDataMethods<'lua, T> { - methods: HashMap>, - meta_methods: HashMap>, + methods: HashMap>, + meta_methods: HashMap>, _type: PhantomData, } @@ -823,7 +820,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> { self.meta_methods.insert(meta, Box::new(function)); } - fn box_method(mut method: M) -> LuaCallback<'lua> + fn box_method(mut method: M) -> Callback<'lua> where M: 'lua + for<'a> FnMut(&'lua Lua, &'a T, MultiValue<'lua>) -> Result>, { @@ -840,7 +837,7 @@ impl<'lua, T: UserData> UserDataMethods<'lua, T> { } - fn box_method_mut(mut method: M) -> LuaCallback<'lua> + fn box_method_mut(mut method: M) -> Callback<'lua> where M: 'lua + for<'a> FnMut(&'lua Lua, &'a mut T, MultiValue<'lua>) -> Result> { @@ -993,7 +990,7 @@ impl Lua { ffi::lua_newtable(state); push_string(state, "__gc"); - ffi::lua_pushcfunction(state, userdata_destructor::); + ffi::lua_pushcfunction(state, userdata_destructor::); ffi::lua_rawset(state, -3); push_string(state, "__metatable"); @@ -1304,7 +1301,7 @@ impl Lua { T::from_lua_multi(value, self) } - fn create_callback_function<'lua>(&'lua self, func: LuaCallback<'lua>) -> Function<'lua> { + fn create_callback_function<'lua>(&'lua self, func: Callback<'lua>) -> Function<'lua> { unsafe extern "C" fn callback_call_impl(state: *mut ffi::lua_State) -> c_int { callback_error(state, || { let lua = Lua { @@ -1313,7 +1310,7 @@ impl Lua { ephemeral: true, }; - let func = &mut *get_userdata::(state, ffi::lua_upvalueindex(1)); + let func = &mut *get_userdata::(state, ffi::lua_upvalueindex(1)); let nargs = ffi::lua_gettop(state); let mut args = MultiValue::new(); @@ -1336,7 +1333,7 @@ impl Lua { stack_guard(self.state, 0, move || { check_stack(self.state, 2); - push_userdata::(self.state, func); + push_userdata::(self.state, func); ffi::lua_pushlightuserdata( self.state, @@ -1404,7 +1401,7 @@ impl Lua { match ffi::lua_type(state, -1) { ffi::LUA_TNIL => { ffi::lua_pop(state, 1); - LuaNil + Nil } ffi::LUA_TBOOLEAN => { diff --git a/src/multi.rs b/src/multi.rs index 046137f..bca9386 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -24,7 +24,7 @@ impl<'lua, T: ToLua<'lua>, E: ToLua<'lua>> ToLuaMulti<'lua> for ::std::result::R match self { Ok(v) => result.push_back(v.to_lua(lua)?), Err(e) => { - result.push_back(LuaNil); + result.push_back(Nil); result.push_back(e.to_lua(lua)?); } } @@ -43,7 +43,7 @@ impl<'lua, T: ToLua<'lua>> ToLuaMulti<'lua> for T { impl<'lua, T: FromLua<'lua>> FromLuaMulti<'lua> for T { fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result { - Ok(T::from_lua(values.pop_front().unwrap_or(LuaNil), lua)?) + Ok(T::from_lua(values.pop_front().unwrap_or(Nil), lua)?) } } @@ -119,7 +119,7 @@ impl<'lua, H: FromLua<'lua>, A, B> FromLuaMulti<'lua> for HCons> where HCons: FromLuaMulti<'lua> { fn from_lua_multi(mut values: MultiValue<'lua>, lua: &'lua Lua) -> Result { - let val = H::from_lua(values.pop_front().unwrap_or(LuaNil), lua)?; + let val = H::from_lua(values.pop_front().unwrap_or(Nil), lua)?; let res = HCons::::from_lua_multi(values, lua)?; Ok(HCons(val, res)) } diff --git a/src/prelude.rs b/src/prelude.rs new file mode 100644 index 0000000..18f80a3 --- /dev/null +++ b/src/prelude.rs @@ -0,0 +1,8 @@ +pub use {Error as LuaError, Result as LuaResult, ExternalError as LuaExternalError, + ExternalResult as LuaExternalResult, Value as LuaValue, Nil as LuaNil, ToLua, FromLua, + MultiValue as LuaMultiValue, ToLuaMulti, FromLuaMulti, Integer as LuaInteger, + Number as LuaNumber, LightUserData as LuaLightUserData, String as LuaString, + Table as LuaTable, TablePairs as LuaTablePairs, TableSequence as LuaTableSequence, + Function as LuaFunction, ThreadStatus as LuaThreadStatus, Thread as LuaThread, + MetaMethod as LuaMetaMethod, UserDataMethods as LuaUserDataMethods, + UserData as LuaUserData, AnyUserData as LuaAnyUserData, Lua}; diff --git a/src/tests.rs b/src/tests.rs index 4b81908..3c5b970 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -5,7 +5,7 @@ use std::os::raw::c_void; use String as LuaString; use { - Lua, Result, LuaExternalError, LightUserData, UserDataMethods, UserData, Table, Thread, + Lua, Result, ExternalError, LightUserData, UserDataMethods, UserData, Table, Thread, ThreadStatus, Error, Function, Value, Variadic, MetaMethod }; From b3b0f17f597b23e2217d690faac1a29cad982d79 Mon Sep 17 00:00:00 2001 From: kyren Date: Mon, 24 Jul 2017 07:30:29 -0400 Subject: [PATCH 6/6] Slight changes for consistency I am not actually sure what the best pattern is to import conflicting standard types, but this is at least consistent. --- src/error.rs | 21 +++++++++++---------- src/multi.rs | 4 +++- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/error.rs b/src/error.rs index a11d84b..9c9f6f7 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,7 @@ use std::fmt; use std::sync::Arc; -use std::error; +use std::error::Error as StdError; +use std::result::Result as StdResult; #[derive(Debug, Clone)] pub enum Error { @@ -29,10 +30,10 @@ pub enum Error { CallbackError(String, Arc), /// Any custom external error type, mostly useful for returning external error types from /// callbacks. - ExternalError(Arc), + ExternalError(Arc), } -pub type Result = ::std::result::Result; +pub type Result = StdResult; impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { @@ -61,7 +62,7 @@ impl fmt::Display for Error { } } -impl error::Error for Error { +impl StdError for Error { fn description(&self) -> &str { match *self { Error::SyntaxError(_) => "lua syntax error", @@ -79,7 +80,7 @@ impl error::Error for Error { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&StdError> { match *self { Error::CallbackError(_, ref cause) => Some(cause.as_ref()), Error::ExternalError(ref err) => err.cause(), @@ -89,7 +90,7 @@ impl error::Error for Error { } impl Error { - pub fn external(err: T) -> Error { + pub fn external(err: T) -> Error { Error::ExternalError(Arc::new(err)) } } @@ -100,11 +101,11 @@ pub trait ExternalError { impl ExternalError for E where - E: Into>, + E: Into>, { fn to_lua_err(self) -> Error { #[derive(Debug)] - struct WrapError(Box); + struct WrapError(Box); impl fmt::Display for WrapError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -112,7 +113,7 @@ where } } - impl error::Error for WrapError { + impl StdError for WrapError { fn description(&self) -> &str { self.0.description() } @@ -126,7 +127,7 @@ pub trait ExternalResult { fn to_lua_err(self) -> Result; } -impl ExternalResult for ::std::result::Result +impl ExternalResult for StdResult where E: ExternalError, { diff --git a/src/multi.rs b/src/multi.rs index bca9386..11c13fc 100644 --- a/src/multi.rs +++ b/src/multi.rs @@ -1,3 +1,5 @@ +use std::result::{Result as StdResult}; + use hlist_macro::{HNil, HCons}; use error::*; @@ -17,7 +19,7 @@ impl<'lua> FromLuaMulti<'lua> for () { /// 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 ::std::result::Result { +impl<'lua, T: ToLua<'lua>, E: ToLua<'lua>> ToLuaMulti<'lua> for StdResult { fn to_lua_multi(self, lua: &'lua Lua) -> Result> { let mut result = MultiValue::new();