diff --git a/examples/callbacks.luau b/examples/callbacks.luau new file mode 100644 index 0000000..77e249e --- /dev/null +++ b/examples/callbacks.luau @@ -0,0 +1,4 @@ +--!nocheck +--!nolint UnknownGlobal + +error("Oh no! Something went very very wrong!") diff --git a/examples/callbacks.rs b/examples/callbacks.rs new file mode 100644 index 0000000..7cc074e --- /dev/null +++ b/examples/callbacks.rs @@ -0,0 +1,24 @@ +use smol_mlua::{ + mlua::prelude::{Lua, LuaResult}, + Callbacks, Runtime, +}; + +const MAIN_SCRIPT: &str = include_str!("./callbacks.luau"); + +pub fn main() -> LuaResult<()> { + // Set up persistent lua environment + let lua = Lua::new(); + + // Load the main script into a runtime + let rt = Runtime::new(&lua)?; + let main = lua.load(MAIN_SCRIPT); + + // Inject default value & error callbacks - this will print lua errors to stderr + Callbacks::default().inject(&lua); + + // Run the main script until completion + rt.push_main(&lua, main, ()); + rt.run_blocking(&lua); + + Ok(()) +} diff --git a/lib/callbacks.rs b/lib/callbacks.rs index 1966b32..1f85048 100644 --- a/lib/callbacks.rs +++ b/lib/callbacks.rs @@ -6,7 +6,6 @@ type ErrorCallback = Box Fn(&'lua Lua, LuaThread<'lua>, LuaError) const FORWARD_VALUE_KEY: &str = "__runtime__forwardValue"; const FORWARD_ERROR_KEY: &str = "__runtime__forwardError"; -#[derive(Default)] pub struct Callbacks { on_value: Option, on_error: Option, @@ -33,6 +32,16 @@ impl Callbacks { self } + pub fn without_value_callback(mut self) -> Self { + self.on_value.take(); + self + } + + pub fn without_error_callback(mut self) -> Self { + self.on_error.take(); + self + } + pub fn inject(self, lua: &Lua) { // Create functions to forward values & errors if let Some(f) = self.on_value { @@ -72,3 +81,17 @@ impl Callbacks { } } } + +impl Default for Callbacks { + fn default() -> Self { + Callbacks { + on_value: Some(Box::new(default_value_callback)), + on_error: Some(Box::new(default_error_callback)), + } + } +} + +fn default_value_callback(_: &Lua, _: LuaThread, _: LuaValue) {} +fn default_error_callback(_: &Lua, _: LuaThread, e: LuaError) { + eprintln!("{e}"); +}