implement ClosureSearcher

expose `UserData` created from Rust

manipulate the `rlua::Context` in Rust and return string to load as chunk

primarily intended to enable constructing Lua modules in Rust
- particularly Lua modules involving `UserData`
This commit is contained in:
Andy Weidenbaum
2021-03-23 14:43:56 +11:00
parent dd283c2316
commit 801a04802a
2 changed files with 136 additions and 1 deletions

View File

@@ -128,6 +128,54 @@ where
}
}
/// Like `StaticSearcher`, but with closures as `modules` values, to facilitate setting
/// up an `rlua::Context` with Rust code.
///
/// Enables exposing `UserData` types to an `rlua::Context`.
///
/// Closures must return an `rlua::Result`-wrapped `&'static str`. This string is
/// subsequently passed into `rlua::Context.load()` and evaluated.
pub struct ClosureSearcher {
/// Closures must accept an `rlua::Context` as their only parameter, and can do with
/// it what they wish. Closures must return an `rlua::Result`-wrapped `&'static str`.
modules: HashMap<&'static str, Box<dyn Fn(Context) -> rlua::Result<&'static str> + Send>>,
globals: RegistryKey,
}
impl ClosureSearcher {
pub fn new(
modules: HashMap<&'static str, Box<dyn Fn(Context) -> rlua::Result<&'static str> + Send>>,
globals: RegistryKey,
) -> Self {
Self { modules, globals }
}
}
impl UserData for ClosureSearcher {
fn add_methods<'lua, M>(methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{
methods.add_meta_method(MetaMethod::Call, |lua_ctx, this, name: String| {
let name = name.as_str();
match this.modules.get(name) {
Some(ref loader) => {
let content = loader(lua_ctx)?;
Ok(Value::Function(
lua_ctx
.load(content)
.set_name(name)?
.set_environment(lua_ctx.registry_value::<Table>(&this.globals)?)?
.into_function()?,
))
}
None => Ok(Value::Nil),
}
});
}
}
/// Extend `rlua::Context` to support `require`ing Lua modules by name.
pub trait AddSearcher {
/// Add a `HashMap` of Lua modules indexed by module name to Luas
@@ -154,6 +202,13 @@ pub trait AddSearcher {
) -> Result<()>
where
P: 'static + AsRef<Path> + Send;
/// Like `add_static_searcher`, but with user-provided closure for `rlua::Context`
/// setup.
fn add_closure_searcher(
&self,
modules: HashMap<&'static str, Box<dyn Fn(Context) -> rlua::Result<&'static str> + Send>>,
) -> Result<()>;
}
impl<'a> AddSearcher for Context<'a> {
@@ -208,4 +263,17 @@ impl<'a> AddSearcher for Context<'a> {
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
fn add_closure_searcher(
&self,
modules: HashMap<&'static str, Box<dyn Fn(Context) -> rlua::Result<&'static str> + Send>>,
) -> Result<()> {
let globals = self.globals();
let searchers: Table = globals.get::<_, Table>("package")?.get("searchers")?;
let registry_key = self.create_registry_value(globals)?;
let searcher = ClosureSearcher::new(modules, registry_key);
searchers
.set(searchers.len()? + 1, searcher)
.map_err(|e| e.into())
}
}