Give Lua::eval a source name param and simplify

This commit is contained in:
Jonas Schievink 2017-07-16 22:53:32 +02:00
parent eafe4c7c30
commit d9098900d1
4 changed files with 34 additions and 47 deletions

View file

@ -37,9 +37,9 @@ fn examples() -> LuaResult<()> {
)?;
assert_eq!(globals.get::<_, String>("global")?, "foobar");
assert_eq!(lua.eval::<i32>("1 + 1")?, 2);
assert_eq!(lua.eval::<bool>("false == false")?, true);
assert_eq!(lua.eval::<i32>("return 1 + 2")?, 3);
assert_eq!(lua.eval::<i32>("1 + 1", None)?, 2);
assert_eq!(lua.eval::<bool>("false == false", None)?, true);
assert_eq!(lua.eval::<i32>("return 1 + 2", None)?, 3);
// You can create and manage lua tables
@ -70,7 +70,7 @@ fn examples() -> LuaResult<()> {
for k, v in pairs(map_table) do
print(k, v)
end
"#,
"#, None
)?;
// You can load lua functions
@ -118,16 +118,18 @@ fn examples() -> LuaResult<()> {
assert_eq!(
lua.eval::<bool>(
r#"check_equal({"a", "b", "c"}, {"a", "b", "c"})"#,
None
)?,
true
);
assert_eq!(
lua.eval::<bool>(
r#"check_equal({"a", "b", "c"}, {"d", "e", "f"})"#,
None
)?,
false
);
assert_eq!(lua.eval::<String>(r#"join("a", "b", "c")"#)?, "abc");
assert_eq!(lua.eval::<String>(r#"join("a", "b", "c")"#, None)?, "abc");
// You can create userdata with methods and metamethods defined on them.
// Here's a worked example that shows many of the features of this API
@ -156,7 +158,7 @@ fn examples() -> LuaResult<()> {
});
globals.set("vec2", vec2_constructor)?;
assert!(lua.eval::<f32>("(vec2(1, 2) + vec2(2, 2)):magnitude()")? - 5.0 < f32::EPSILON);
assert!(lua.eval::<f32>("(vec2(1, 2) + vec2(2, 2)):magnitude()", None)? - 5.0 < f32::EPSILON);
Ok(())
}

View file

@ -20,7 +20,7 @@ fn main() {
loop {
stdin.read_line(&mut line).unwrap();
match lua.eval::<LuaMultiValue>(&line) {
match lua.eval::<LuaMultiValue>(&line, None) {
Ok(values) => {
println!(
"{}",

View file

@ -187,7 +187,7 @@ impl<'lua> LuaString<'lua> {
/// let version: LuaString = globals.get("_VERSION").unwrap();
/// assert!(version.to_str().unwrap().contains("Lua"));
///
/// let non_utf8: LuaString = lua.eval(r#" "test\xff" "#).unwrap();
/// let non_utf8: LuaString = lua.eval(r#" "test\xff" "#, None).unwrap();
/// assert!(non_utf8.to_str().is_err());
/// # }
/// ```
@ -622,7 +622,7 @@ impl<'lua> LuaThread<'lua> {
/// assert(yieldarg == 43)
/// return 987
/// end)
/// "#).unwrap();
/// "#, None).unwrap();
///
/// assert_eq!(thread.resume::<_, u32>(42).unwrap(), 123);
/// assert_eq!(thread.resume::<_, u32>(43).unwrap(), 987);
@ -1084,33 +1084,14 @@ impl Lua {
///
/// If `source` is an expression, returns the value it evaluates to. Otherwise, returns the
/// values returned by the chunk (if any).
pub fn eval<'lua, R: FromLuaMulti<'lua>>(&'lua self, source: &str) -> LuaResult<R> {
unsafe {
stack_err_guard(self.state, 0, || {
// 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.
let return_source = "return ".to_owned() + source;
let mut res = ffi::luaL_loadbuffer(
self.state,
return_source.as_ptr() as *const c_char,
return_source.len(),
ptr::null(),
);
if res == ffi::LUA_ERRSYNTAX {
ffi::lua_pop(self.state, 1);
res = ffi::luaL_loadbuffer(
self.state,
source.as_ptr() as *const c_char,
source.len(),
ptr::null(),
);
}
handle_error(self.state, res)?;
LuaFunction(self.pop_ref(self.state)).call(())
})
}
pub fn eval<'lua, R: FromLuaMulti<'lua>>(
&'lua self,
source: &str,
name: Option<&str>
) -> LuaResult<R> {
self.load(&format!("return {}", source), name)
.or_else(|_| self.load(source, name))?
.call(())
}
/// Pass a `&str` slice to Lua, creating and returning a interned Lua string.

View file

@ -64,10 +64,10 @@ fn test_exec() {
#[test]
fn test_eval() {
let lua = Lua::new();
assert_eq!(lua.eval::<i32>("1 + 1").unwrap(), 2);
assert_eq!(lua.eval::<bool>("false == false").unwrap(), true);
assert_eq!(lua.eval::<i32>("return 1 + 2").unwrap(), 3);
match lua.eval::<()>("if true then") {
assert_eq!(lua.eval::<i32>("1 + 1", None).unwrap(), 2);
assert_eq!(lua.eval::<bool>("false == false", None).unwrap(), true);
assert_eq!(lua.eval::<i32>("return 1 + 2", None).unwrap(), 3);
match lua.eval::<()>("if true then", None) {
Err(LuaError::IncompleteStatement(_)) => {}
r => panic!("expected IncompleteStatement, got {:?}", r),
}
@ -323,11 +323,11 @@ fn test_metamethods() {
let globals = lua.globals();
globals.set("userdata1", UserData(7)).unwrap();
globals.set("userdata2", UserData(3)).unwrap();
assert_eq!(lua.eval::<UserData>("userdata1 + userdata2").unwrap().0, 10);
assert_eq!(lua.eval::<UserData>("userdata1 - userdata2").unwrap().0, 4);
assert_eq!(lua.eval::<i64>("userdata1:get()").unwrap(), 7);
assert_eq!(lua.eval::<i64>("userdata2.inner").unwrap(), 3);
assert!(lua.eval::<()>("userdata2.nonexist_field").is_err());
assert_eq!(lua.eval::<UserData>("userdata1 + userdata2", None).unwrap().0, 10);
assert_eq!(lua.eval::<UserData>("userdata1 - userdata2", None).unwrap().0, 4);
assert_eq!(lua.eval::<i64>("userdata1:get()", None).unwrap(), 7);
assert_eq!(lua.eval::<i64>("userdata2.inner", None).unwrap(), 3);
assert!(lua.eval::<()>("userdata2.nonexist_field", None).is_err());
}
#[test]
@ -528,12 +528,12 @@ fn test_error() {
assert!(return_string_error.call::<_, LuaError>(()).is_ok());
match lua.eval::<()>("if youre happy and you know it syntax error") {
match lua.eval::<()>("if youre happy and you know it syntax error", None) {
Err(LuaError::SyntaxError(_)) => {}
Err(_) => panic!("error is not LuaSyntaxError::Syntax kind"),
_ => panic!("error not returned"),
}
match lua.eval::<()>("function i_will_finish_what_i()") {
match lua.eval::<()>("function i_will_finish_what_i()", None) {
Err(LuaError::IncompleteStatement(_)) => {}
Err(_) => panic!("error is not LuaSyntaxError::IncompleteStatement kind"),
_ => panic!("error not returned"),
@ -610,6 +610,7 @@ fn test_thread() {
return sum
end
"#,
None
).unwrap(),
);
@ -634,6 +635,7 @@ fn test_thread() {
end
end
"#,
None
).unwrap(),
);
@ -653,6 +655,7 @@ fn test_thread() {
end
end)
"#,
None
).unwrap();
assert_eq!(thread.status(), LuaThreadStatus::Active);
assert_eq!(thread.resume::<_, i64>(()).unwrap(), 42);
@ -666,6 +669,7 @@ fn test_thread() {
return 987
end)
"#,
None
).unwrap();
assert_eq!(thread.resume::<_, u32>(42).unwrap(), 123);