add FunctionLoader and StaticFunctionSearcher

an alternative to boxing closures
This commit is contained in:
Andy Weidenbaum
2021-05-12 21:01:21 +10:00
parent 76425c0aeb
commit 10391c419a
2 changed files with 261 additions and 4 deletions

View File

@@ -160,6 +160,14 @@ fn module_reloading_works() {
assert_eq!("hello lume", hello);
}
fn read_lume_to_string() -> String {
r#"return "hello lume""#.to_string()
}
fn read_lume_to_str() -> &'static str {
r#"return "hello lume""#
}
#[test]
fn add_closure_searcher_works() {
let lua = Lua::new();
@@ -288,10 +296,107 @@ impl UserData for Instrument {
}
}
fn read_lume_to_string() -> String {
r#"return "hello lume""#.to_string()
#[test]
fn add_function_searcher_works() {
let lua = Lua::new();
let mut modules: HashMap<
String,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
> = HashMap::new();
modules.insert("cartridge".to_string(), cartridge_loader);
let title = lua
.context::<_, Result<String>>(|lua_ctx| {
lua_ctx.add_function_searcher(modules)?;
// Ensure global variable `cartridge` is unset.
let nil: String = lua_ctx.load("return type(cartridge)").eval()?;
assert_eq!(nil, "nil");
Ok(lua_ctx
.load(
r#"local cartridge = require("cartridge")
local smash = cartridge.pick()
return smash:play()"#,
)
.eval()?)
})
.unwrap();
assert_eq!(title, "Super Smash Brothers 64");
}
fn read_lume_to_str() -> &'static str {
r#"return "hello lume""#
#[test]
fn add_static_function_searcher_works() {
let lua = Lua::new();
let mut modules: HashMap<
&'static str,
for<'ctx> fn(Context<'ctx>, Table<'ctx>, &str) -> rlua::Result<Function<'ctx>>,
> = HashMap::new();
modules.insert("cartridge", cartridge_loader);
let title = lua
.context::<_, Result<String>>(|lua_ctx| {
lua_ctx.add_static_function_searcher(modules)?;
// Ensure global variable `cartridge` is unset.
let nil: String = lua_ctx.load("return type(cartridge)").eval()?;
assert_eq!(nil, "nil");
Ok(lua_ctx
.load(
r#"local cartridge = require("cartridge")
local smash = cartridge.pick()
return smash:play()"#,
)
.eval()?)
})
.unwrap();
assert_eq!(title, "Super Smash Brothers 64");
}
struct Cartridge {
title: String,
}
impl Cartridge {
pub fn pick() -> Self {
let title = "Super Smash Brothers 64".to_string();
Self { title }
}
pub fn play(&self) -> String {
self.title.clone()
}
}
impl UserData for Cartridge {
fn add_methods<'lua, M>(methods: &mut M)
where
M: UserDataMethods<'lua, Self>,
{
methods.add_method("play", |_, cartridge, ()| Ok(cartridge.play()));
}
}
fn cartridge_loader<'ctx>(
lua_ctx: Context<'ctx>,
env: Table<'ctx>,
name: &str,
) -> rlua::Result<Function<'ctx>> {
let globals = lua_ctx.globals();
let pick = lua_ctx.create_function(|_, ()| Ok(Cartridge::pick()))?;
let tbl = lua_ctx.create_table()?;
tbl.set("pick", pick)?;
globals.set("cartridge", tbl)?;
Ok(lua_ctx
.load("return cartridge")
.set_name(name)?
.set_environment(env)?
.into_function()?)
}