diff --git a/src/lune/mod.rs b/src/lune/mod.rs index 30080cf..bf41a4b 100644 --- a/src/lune/mod.rs +++ b/src/lune/mod.rs @@ -2,6 +2,7 @@ use std::process::ExitCode; mod error; mod scheduler; +mod util; use self::scheduler::Scheduler; diff --git a/src/lune/util/mod.rs b/src/lune/util/mod.rs new file mode 100644 index 0000000..7de66f3 --- /dev/null +++ b/src/lune/util/mod.rs @@ -0,0 +1,3 @@ +mod table_builder; + +pub use table_builder::TableBuilder; diff --git a/src/lune/util/table_builder.rs b/src/lune/util/table_builder.rs new file mode 100644 index 0000000..9cc6a4e --- /dev/null +++ b/src/lune/util/table_builder.rs @@ -0,0 +1,68 @@ +#![allow(dead_code)] + +use std::future::Future; + +use mlua::prelude::*; + +use crate::lune::scheduler::LuaSchedulerExt; + +pub struct TableBuilder<'lua> { + lua: &'lua Lua, + tab: LuaTable<'lua>, +} + +impl<'lua> TableBuilder<'lua> { + pub fn new(lua: &'lua Lua) -> LuaResult { + let tab = lua.create_table()?; + Ok(Self { lua, tab }) + } + + pub fn with_value(self, key: K, value: V) -> LuaResult + where + K: IntoLua<'lua>, + V: IntoLua<'lua>, + { + self.tab.raw_set(key, value)?; + Ok(self) + } + + pub fn with_function(self, key: K, func: F) -> LuaResult + where + K: IntoLua<'lua>, + A: FromLuaMulti<'lua>, + R: IntoLuaMulti<'lua>, + F: Fn(&'lua Lua, A) -> LuaResult + 'static, + { + let f = self.lua.create_function(func)?; + self.with_value(key, LuaValue::Function(f)) + } + + pub fn with_metatable(self, table: LuaTable) -> LuaResult { + self.tab.set_metatable(Some(table)); + Ok(self) + } + + pub fn build_readonly(self) -> LuaResult> { + self.tab.set_readonly(true); + Ok(self.tab) + } + + pub fn build(self) -> LuaResult> { + Ok(self.tab) + } +} + +// FIXME: Remove static lifetimes here when possible and move into above impl +impl TableBuilder<'static> { + pub fn with_async_function(self, key: K, func: F) -> LuaResult + where + K: IntoLua<'static>, + A: FromLuaMulti<'static>, + R: IntoLuaMulti<'static>, + F: Fn(&'static Lua, A) -> FR + 'static, + FR: Future> + 'static, + { + let f = self.lua.create_async_function(func)?; + self.with_value(key, LuaValue::Function(f)) + } +}