From b4bbc0630a75673c1601adc304834a7d729512fd Mon Sep 17 00:00:00 2001 From: Filip Tibell Date: Fri, 18 Aug 2023 13:50:04 -0500 Subject: [PATCH] Add table builder util --- src/lune/mod.rs | 1 + src/lune/util/mod.rs | 3 ++ src/lune/util/table_builder.rs | 68 ++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 src/lune/util/mod.rs create mode 100644 src/lune/util/table_builder.rs 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)) + } +}