From 4763d8ce3b833df1e7321a407b08666f69657fdb Mon Sep 17 00:00:00 2001 From: Nathan Reiner Date: Thu, 8 Aug 2024 21:46:54 +0200 Subject: refactore runnable --- src/lua/mod.rs | 1 + src/lua/ownedfunction.rs | 12 +++++++++++- src/lua/runnable.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/lua/runnable.rs (limited to 'src/lua') diff --git a/src/lua/mod.rs b/src/lua/mod.rs index e10d83b..afa6171 100644 --- a/src/lua/mod.rs +++ b/src/lua/mod.rs @@ -19,6 +19,7 @@ pub mod evalsto; pub mod iobuffer; pub mod ownedfunction; pub mod runtime; +pub mod runnable; lazy_static! { static ref LUA: Mutex = { diff --git a/src/lua/ownedfunction.rs b/src/lua/ownedfunction.rs index a8d81cf..54e39df 100644 --- a/src/lua/ownedfunction.rs +++ b/src/lua/ownedfunction.rs @@ -1,4 +1,4 @@ -use mlua::{Function, Lua, RegistryKey, Value}; +use mlua::{Error, FromLua, Function, Lua, RegistryKey, Value}; #[derive(Debug)] pub struct OwnedFunction { @@ -15,3 +15,13 @@ impl OwnedFunction { lua.registry_value(&self.key).unwrap() } } + +impl<'lua> FromLua<'lua> for OwnedFunction { + fn from_lua(value: Value<'lua>, lua: &'lua Lua) -> mlua::prelude::LuaResult { + if value.is_function() { + Ok(OwnedFunction::new(value, lua)) + } else { + Err(Error::runtime("value needs to be function")) + } + } +} diff --git a/src/lua/runnable.rs b/src/lua/runnable.rs new file mode 100644 index 0000000..adda512 --- /dev/null +++ b/src/lua/runnable.rs @@ -0,0 +1,42 @@ +use mlua::{FromLuaMulti, Function, IntoLuaMulti, Lua, Result}; + +use super::ownedfunction::OwnedFunction; + +pub trait Runnable +where + Self: Send, +{ + fn run<'lua>(&self, arg: A, lua: &'lua Lua) -> Result + where + A: IntoLuaMulti<'lua>, + R: FromLuaMulti<'lua>; +} + +impl Runnable for T +where + T: Fn(A) -> R, + Self: Send, +{ + fn run<'lua>(&self, arg: A, _: &'lua Lua) -> Result + where + A: IntoLuaMulti<'lua>, + R: FromLuaMulti<'lua>, + { + Ok(self(arg)) + } +} + +impl Runnable for OwnedFunction +where + Self: Send, +{ + fn run<'lua>(&self, arg: A, lua: &'lua Lua) -> Result + where + A: IntoLuaMulti<'lua>, + R: FromLuaMulti<'lua>, + { + let func: Function = self.get(lua); + func.call::(arg) + } +} + -- cgit v1.2.3-70-g09d2