Add default error callback and callbacks example

This commit is contained in:
Filip Tibell 2024-01-19 23:07:23 +01:00
parent c87e0c4c71
commit f33bb81324
No known key found for this signature in database
3 changed files with 52 additions and 1 deletions

4
examples/callbacks.luau Normal file
View file

@ -0,0 +1,4 @@
--!nocheck
--!nolint UnknownGlobal
error("Oh no! Something went very very wrong!")

24
examples/callbacks.rs Normal file
View file

@ -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(())
}

View file

@ -6,7 +6,6 @@ type ErrorCallback = Box<dyn for<'lua> 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<ValueCallback>,
on_error: Option<ErrorCallback>,
@ -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}");
}