2024-09-18 18:47:38 -07:00
|
|
|
use crate::context::Context;
|
|
|
|
|
2024-09-17 17:16:57 -07:00
|
|
|
pub struct Runner{
|
|
|
|
lua:mlua::Lua,
|
2024-09-16 18:54:04 -07:00
|
|
|
}
|
2024-09-18 18:47:38 -07:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum Error{
|
2024-09-20 18:01:25 -07:00
|
|
|
Lua{
|
|
|
|
source:String,
|
|
|
|
error:mlua::Error
|
|
|
|
},
|
2024-09-21 15:03:27 -07:00
|
|
|
RustLua(mlua::Error),
|
2024-09-21 13:26:20 -07:00
|
|
|
Script(super::instance::GetScriptError),
|
2024-09-18 18:47:38 -07:00
|
|
|
}
|
2024-09-21 15:03:27 -07:00
|
|
|
impl std::fmt::Display for Error{
|
|
|
|
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
2024-09-18 18:47:38 -07:00
|
|
|
match self{
|
2024-09-21 15:03:27 -07:00
|
|
|
Self::Lua{source,error:mlua::Error::RuntimeError(s)}=>write!(f,"lua error: {s}\nsource:{source}"),
|
|
|
|
Self::RustLua(mlua::Error::RuntimeError(s))=>write!(f,"rust-side lua error: {s}"),
|
|
|
|
other=>write!(f,"{other:?}"),
|
2024-09-18 18:47:38 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-09-16 18:54:04 -07:00
|
|
|
|
2024-09-17 17:16:57 -07:00
|
|
|
fn init(lua:&mlua::Lua)->mlua::Result<()>{
|
2024-09-17 17:17:12 -07:00
|
|
|
lua.sandbox(true)?;
|
|
|
|
|
|
|
|
//global environment
|
|
|
|
let globals=lua.globals();
|
|
|
|
|
2024-10-03 16:26:23 -07:00
|
|
|
super::vector3::set_globals(lua,&globals)?;
|
|
|
|
super::cframe::set_globals(lua,&globals)?;
|
2024-09-17 17:17:12 -07:00
|
|
|
|
2024-09-16 19:01:16 -07:00
|
|
|
Ok(())
|
2024-09-16 18:54:04 -07:00
|
|
|
}
|
2024-09-17 17:16:57 -07:00
|
|
|
|
|
|
|
impl Runner{
|
2024-09-21 15:03:27 -07:00
|
|
|
pub fn new()->Result<Self,Error>{
|
2024-09-17 17:16:57 -07:00
|
|
|
let runner=Self{
|
|
|
|
lua:mlua::Lua::new(),
|
|
|
|
};
|
2024-09-21 15:03:27 -07:00
|
|
|
init(&runner.lua).map_err(Error::RustLua)?;
|
2024-09-17 17:16:57 -07:00
|
|
|
Ok(runner)
|
|
|
|
}
|
2024-09-21 13:26:20 -07:00
|
|
|
pub fn run_script(&self,script:super::instance::Script,context:&mut Context)->Result<(),Error>{
|
|
|
|
let (name,source)=script.get_name_source(context).map_err(Error::Script)?;
|
2024-09-21 15:03:27 -07:00
|
|
|
self.lua.globals().set("script",script).map_err(Error::RustLua)?;
|
2024-09-20 13:51:17 -07:00
|
|
|
//this makes set_app_data shut up about the lifetime
|
|
|
|
self.lua.set_app_data::<&'static mut rbx_dom_weak::WeakDom>(unsafe{core::mem::transmute(&mut context.dom)});
|
2024-09-20 18:01:25 -07:00
|
|
|
let r=self.lua.load(source.as_str())
|
2024-09-20 13:51:17 -07:00
|
|
|
.set_name(name)
|
2024-09-20 18:01:25 -07:00
|
|
|
.exec().map_err(|error|Error::Lua{source,error});
|
2024-09-20 13:51:17 -07:00
|
|
|
self.lua.remove_app_data::<&'static mut rbx_dom_weak::WeakDom>();
|
2024-09-20 18:01:25 -07:00
|
|
|
r?;
|
2024-09-20 13:51:17 -07:00
|
|
|
Ok(())
|
2024-09-17 17:16:57 -07:00
|
|
|
}
|
|
|
|
}
|