Compare commits
8 Commits
2d4a19dd0b
...
22d6087b3c
Author | SHA1 | Date | |
---|---|---|---|
22d6087b3c | |||
ded3cb4700 | |||
a8b29d8fed | |||
3181912bde | |||
70c78b66bd | |||
5997d312cd | |||
fe529c3b0a | |||
14fdcd630e |
@ -4,11 +4,12 @@ use mlua::{FromLua,FromLuaMulti,IntoLua,IntoLuaMulti};
|
||||
use rbx_types::Ref;
|
||||
use rbx_dom_weak::{InstanceBuilder,WeakDom};
|
||||
|
||||
use super::vector3::Vector3;
|
||||
use crate::runner::vector3::Vector3;
|
||||
|
||||
pub fn set_globals(lua:&mlua::Lua,globals:&mlua::Table)->Result<(),mlua::Error>{
|
||||
//class functions store
|
||||
lua.set_app_data(ClassFunctions::default());
|
||||
lua.set_app_data(ClassMethodsStore::default());
|
||||
lua.set_app_data(InstanceValueStore::default());
|
||||
|
||||
let instance_table=lua.create_table()?;
|
||||
|
||||
@ -16,7 +17,7 @@ pub fn set_globals(lua:&mlua::Lua,globals:&mlua::Table)->Result<(),mlua::Error>{
|
||||
instance_table.raw_set("new",
|
||||
lua.create_function(|lua,(class_name,parent):(mlua::String,Option<Instance>)|{
|
||||
let class_name_str=&*class_name.to_str()?;
|
||||
let parent=parent.ok_or(mlua::Error::runtime("Nil Parent not yet supported"))?;
|
||||
let parent=parent.ok_or_else(||mlua::Error::runtime("Nil Parent not yet supported"))?;
|
||||
dom_mut(lua,|dom|{
|
||||
//TODO: Nil instances
|
||||
Ok(Instance::new(dom.insert(parent.referent,InstanceBuilder::new(class_name_str))))
|
||||
@ -30,14 +31,10 @@ pub fn set_globals(lua:&mlua::Lua,globals:&mlua::Table)->Result<(),mlua::Error>{
|
||||
}
|
||||
|
||||
// LMAO look at this function!
|
||||
fn dom_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut WeakDom)->mlua::Result<T>)->mlua::Result<T>{
|
||||
let mut dom=lua.app_data_mut::<&'static mut WeakDom>().ok_or(mlua::Error::runtime("DataModel missing"))?;
|
||||
pub fn dom_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut WeakDom)->mlua::Result<T>)->mlua::Result<T>{
|
||||
let mut dom=lua.app_data_mut::<&'static mut WeakDom>().ok_or_else(||mlua::Error::runtime("DataModel missing"))?;
|
||||
f(&mut *dom)
|
||||
}
|
||||
fn class_functions_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut ClassFunctions)->mlua::Result<T>)->mlua::Result<T>{
|
||||
let mut cf=lua.app_data_mut::<ClassFunctions>().ok_or(mlua::Error::runtime("ClassFunctions missing"))?;
|
||||
f(&mut *cf)
|
||||
}
|
||||
|
||||
fn coerce_float32(value:&mlua::Value)->Option<f32>{
|
||||
match value{
|
||||
@ -92,10 +89,10 @@ impl Instance{
|
||||
Self{referent}
|
||||
}
|
||||
pub fn get<'a>(&self,dom:&'a WeakDom)->mlua::Result<&'a rbx_dom_weak::Instance>{
|
||||
dom.get_by_ref(self.referent).ok_or(mlua::Error::runtime("Instance missing"))
|
||||
dom.get_by_ref(self.referent).ok_or_else(||mlua::Error::runtime("Instance missing"))
|
||||
}
|
||||
pub fn get_mut<'a>(&self,dom:&'a mut WeakDom)->mlua::Result<&'a mut rbx_dom_weak::Instance>{
|
||||
dom.get_by_ref_mut(self.referent).ok_or(mlua::Error::runtime("Instance missing"))
|
||||
dom.get_by_ref_mut(self.referent).ok_or_else(||mlua::Error::runtime("Instance missing"))
|
||||
}
|
||||
}
|
||||
type_from_lua_userdata!(Instance);
|
||||
@ -128,7 +125,7 @@ impl mlua::UserData for Instance{
|
||||
})
|
||||
});
|
||||
fields.add_field_method_set("Parent",|lua,this,val:Option<Instance>|{
|
||||
let parent=val.ok_or(mlua::Error::runtime("Nil Parent not yet supported"))?;
|
||||
let parent=val.ok_or_else(||mlua::Error::runtime("Nil Parent not yet supported"))?;
|
||||
dom_mut(lua,|dom|{
|
||||
dom.transfer_within(this.referent,parent.referent);
|
||||
Ok(())
|
||||
@ -234,7 +231,7 @@ impl mlua::UserData for Instance{
|
||||
let instance=this.get(dom)?;
|
||||
//println!("__index t={} i={index:?}",instance.name);
|
||||
let db=rbx_reflection_database::get();
|
||||
let class=db.classes.get(instance.class.as_str()).ok_or(mlua::Error::runtime("Class missing"))?;
|
||||
let class=db.classes.get(instance.class.as_str()).ok_or_else(||mlua::Error::runtime("Class missing"))?;
|
||||
//Find existing property
|
||||
match instance.properties.get(index_str)
|
||||
.cloned()
|
||||
@ -256,13 +253,13 @@ impl mlua::UserData for Instance{
|
||||
Some(rbx_types::Variant::Float32(val))=>return val.into_lua(lua),
|
||||
Some(rbx_types::Variant::Float64(val))=>return val.into_lua(lua),
|
||||
Some(rbx_types::Variant::Ref(val))=>return Instance::new(val).into_lua(lua),
|
||||
Some(rbx_types::Variant::CFrame(cf))=>return Into::<super::cframe::CFrame>::into(cf).into_lua(lua),
|
||||
Some(rbx_types::Variant::Vector3(v))=>return Into::<super::vector3::Vector3>::into(v).into_lua(lua),
|
||||
Some(rbx_types::Variant::CFrame(cf))=>return Into::<crate::runner::cframe::CFrame>::into(cf).into_lua(lua),
|
||||
Some(rbx_types::Variant::Vector3(v))=>return Into::<crate::runner::vector3::Vector3>::into(v).into_lua(lua),
|
||||
None=>(),
|
||||
other=>return Err(mlua::Error::runtime(format!("Instance.__index Unsupported property type instance={} index={index_str} value={other:?}",instance.name))),
|
||||
}
|
||||
//find a function with a matching name
|
||||
if let Some(function)=class_functions_mut(lua,|cf|{
|
||||
if let Some(function)=class_methods_store_mut(lua,|cf|{
|
||||
let mut iter=SuperClassIter{
|
||||
database:db,
|
||||
descriptor:Some(class),
|
||||
@ -275,6 +272,17 @@ impl mlua::UserData for Instance{
|
||||
})?{
|
||||
return function.into_lua(lua);
|
||||
}
|
||||
|
||||
//find or create an associated userdata object
|
||||
if let Some(value)=instance_value_store_mut(lua,|ivs|{
|
||||
//TODO: walk class tree somehow
|
||||
match ivs.get_or_create_instance_values(&instance){
|
||||
Some(mut instance_values)=>instance_values.get_or_create_value(lua,index_str),
|
||||
None=>Ok(None)
|
||||
}
|
||||
})?{
|
||||
return value.into_lua(lua);
|
||||
}
|
||||
//find a child with a matching name
|
||||
find_first_child(dom,instance,index_str)
|
||||
.map(|instance|Instance::new(instance.referent()))
|
||||
@ -287,19 +295,19 @@ impl mlua::UserData for Instance{
|
||||
//println!("__newindex t={} i={index:?} v={value:?}",instance.name);
|
||||
let index_str=&*index.to_str()?;
|
||||
let db=rbx_reflection_database::get();
|
||||
let class=db.classes.get(instance.class.as_str()).ok_or(mlua::Error::runtime("Class missing"))?;
|
||||
let class=db.classes.get(instance.class.as_str()).ok_or_else(||mlua::Error::runtime("Class missing"))?;
|
||||
let mut iter=SuperClassIter{
|
||||
database:db,
|
||||
descriptor:Some(class),
|
||||
};
|
||||
let property=iter.find_map(|cls|cls.properties.get(index_str)).ok_or(mlua::Error::runtime(format!("Property '{index_str}' missing on class '{}'",class.name)))?;
|
||||
let property=iter.find_map(|cls|cls.properties.get(index_str)).ok_or_else(||mlua::Error::runtime(format!("Property '{index_str}' missing on class '{}'",class.name)))?;
|
||||
match &property.data_type{
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::Vector3)=>{
|
||||
let typed_value:Vector3=*value.as_userdata().ok_or(mlua::Error::runtime("Expected Userdata"))?.borrow()?;
|
||||
let typed_value:Vector3=*value.as_userdata().ok_or_else(||mlua::Error::runtime("Expected Userdata"))?.borrow()?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::Vector3(typed_value.into()));
|
||||
},
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::Float32)=>{
|
||||
let typed_value:f32=coerce_float32(&value).ok_or(mlua::Error::runtime("Expected f32"))?;
|
||||
let typed_value:f32=coerce_float32(&value).ok_or_else(||mlua::Error::runtime("Expected f32"))?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::Float32(typed_value));
|
||||
},
|
||||
rbx_reflection::DataType::Enum(enum_name)=>{
|
||||
@ -307,11 +315,11 @@ impl mlua::UserData for Instance{
|
||||
&mlua::Value::Integer(int)=>Ok(rbx_types::Enum::from_u32(int as u32)),
|
||||
&mlua::Value::Number(num)=>Ok(rbx_types::Enum::from_u32(num as u32)),
|
||||
mlua::Value::String(s)=>{
|
||||
let e=db.enums.get(enum_name).ok_or(mlua::Error::runtime("Database DataType Enum name does not exist"))?;
|
||||
Ok(rbx_types::Enum::from_u32(*e.items.get(&*s.to_str()?).ok_or(mlua::Error::runtime("Invalid enum item"))?))
|
||||
let e=db.enums.get(enum_name).ok_or_else(||mlua::Error::runtime("Database DataType Enum name does not exist"))?;
|
||||
Ok(rbx_types::Enum::from_u32(*e.items.get(&*s.to_str()?).ok_or_else(||mlua::Error::runtime("Invalid enum item"))?))
|
||||
},
|
||||
mlua::Value::UserData(any_user_data)=>{
|
||||
let e:super::r#enum::Enum=*any_user_data.borrow()?;
|
||||
let e:crate::runner::r#enum::Enum=*any_user_data.borrow()?;
|
||||
Ok(e.into())
|
||||
},
|
||||
_=>Err(mlua::Error::runtime("Expected Enum")),
|
||||
@ -319,23 +327,23 @@ impl mlua::UserData for Instance{
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::Enum(typed_value));
|
||||
},
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::Color3)=>{
|
||||
let typed_value:super::color3::Color3=*value.as_userdata().ok_or(mlua::Error::runtime("Expected Color3"))?.borrow()?;
|
||||
let typed_value:crate::runner::color3::Color3=*value.as_userdata().ok_or_else(||mlua::Error::runtime("Expected Color3"))?.borrow()?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::Color3(typed_value.into()));
|
||||
},
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::Bool)=>{
|
||||
let typed_value=value.as_boolean().ok_or(mlua::Error::runtime("Expected boolean"))?;
|
||||
let typed_value=value.as_boolean().ok_or_else(||mlua::Error::runtime("Expected boolean"))?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::Bool(typed_value));
|
||||
},
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::String)=>{
|
||||
let typed_value=value.as_str().ok_or(mlua::Error::runtime("Expected boolean"))?;
|
||||
let typed_value=value.as_str().ok_or_else(||mlua::Error::runtime("Expected boolean"))?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::String(typed_value.to_owned()));
|
||||
},
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::NumberSequence)=>{
|
||||
let typed_value:super::number_sequence::NumberSequence=*value.as_userdata().ok_or(mlua::Error::runtime("Expected NumberSequence"))?.borrow()?;
|
||||
let typed_value:crate::runner::number_sequence::NumberSequence=*value.as_userdata().ok_or_else(||mlua::Error::runtime("Expected NumberSequence"))?.borrow()?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::NumberSequence(typed_value.into()));
|
||||
},
|
||||
rbx_reflection::DataType::Value(rbx_types::VariantType::ColorSequence)=>{
|
||||
let typed_value:super::color_sequence::ColorSequence=*value.as_userdata().ok_or(mlua::Error::runtime("Expected ColorSequence"))?.borrow()?;
|
||||
let typed_value:crate::runner::color_sequence::ColorSequence=*value.as_userdata().ok_or_else(||mlua::Error::runtime("Expected ColorSequence"))?.borrow()?;
|
||||
instance.properties.insert(index_str.to_owned(),rbx_types::Variant::ColorSequence(typed_value.into()));
|
||||
},
|
||||
other=>return Err(mlua::Error::runtime(format!("Unimplemented property type: {other:?}"))),
|
||||
@ -369,12 +377,13 @@ static CLASS_FUNCTION_DATABASE:CFD=phf::phf_map!{
|
||||
"GetService"=>cf!(|lua,_this,service:mlua::String|{
|
||||
dom_mut(lua,|dom|{
|
||||
//dom.root_ref()==this.referent ?
|
||||
match &*service.to_str()?{
|
||||
"Lighting"=>{
|
||||
let referent=find_first_child_of_class(dom,dom.root(),"Lighting")
|
||||
let service=&*service.to_str()?;
|
||||
match service{
|
||||
"Lighting"|"RunService"=>{
|
||||
let referent=find_first_child_of_class(dom,dom.root(),service)
|
||||
.map(|instance|instance.referent())
|
||||
.unwrap_or_else(||
|
||||
dom.insert(dom.root_ref(),InstanceBuilder::new("Lighting"))
|
||||
dom.insert(dom.root_ref(),InstanceBuilder::new(service))
|
||||
);
|
||||
Ok(Instance::new(referent))
|
||||
},
|
||||
@ -384,21 +393,21 @@ static CLASS_FUNCTION_DATABASE:CFD=phf::phf_map!{
|
||||
}),
|
||||
},
|
||||
"Terrain"=>phf::phf_map!{
|
||||
"FillBlock"=>cf!(|_lua,_,_:(super::cframe::CFrame,Vector3,super::r#enum::Enum)|mlua::Result::Ok(()))
|
||||
"FillBlock"=>cf!(|_lua,_,_:(crate::runner::cframe::CFrame,Vector3,crate::runner::r#enum::Enum)|mlua::Result::Ok(()))
|
||||
},
|
||||
};
|
||||
|
||||
/// A store of created functions for each Roblox class.
|
||||
/// Functions are created the first time they are accessed and stored in this data structure.
|
||||
#[derive(Default)]
|
||||
struct ClassFunctions{
|
||||
struct ClassMethodsStore{
|
||||
classes:HashMap<&'static str,//ClassName
|
||||
HashMap<&'static str,//Method name
|
||||
mlua::Function
|
||||
>
|
||||
>
|
||||
}
|
||||
impl ClassFunctions{
|
||||
impl ClassMethodsStore{
|
||||
/// return self.classes[class] or create the ClassMethods and then return it
|
||||
fn get_or_create_class_methods(&mut self,class:&str)->Option<ClassMethods>{
|
||||
// Use get_entry to get the &'static str keys of the database
|
||||
@ -433,6 +442,10 @@ impl ClassMethods<'_>{
|
||||
})
|
||||
}
|
||||
}
|
||||
fn class_methods_store_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut ClassMethodsStore)->mlua::Result<T>)->mlua::Result<T>{
|
||||
let mut cf=lua.app_data_mut::<ClassMethodsStore>().ok_or_else(||mlua::Error::runtime("ClassMethodsStore missing"))?;
|
||||
f(&mut *cf)
|
||||
}
|
||||
|
||||
/// A virtual property pointer definition shorthand.
|
||||
type VirtualPropertyFunctionPointer=fn(&rbx_types::Variant)->Option<rbx_types::Variant>;
|
||||
@ -481,3 +494,64 @@ fn find_virtual_property(
|
||||
//Transform Source property with provided function
|
||||
(virtual_property.pointer)(variant)
|
||||
}
|
||||
|
||||
// lazy-loaded per-instance userdata values
|
||||
// This whole thing is a bad idea and a garbage collection nightmare.
|
||||
// TODO: recreate rbx_dom_weak with my own instance type that owns this data.
|
||||
type CreateUserData=fn(&mlua::Lua)->mlua::Result<mlua::AnyUserData>;
|
||||
type LUD=phf::Map<&'static str,// Class name
|
||||
phf::Map<&'static str,// Value name
|
||||
CreateUserData
|
||||
>
|
||||
>;
|
||||
static LAZY_USER_DATA:LUD=phf::phf_map!{
|
||||
"RunService"=>phf::phf_map!{
|
||||
"RenderStepped"=>|lua|{
|
||||
lua.create_any_userdata(crate::runner::script_signal::ScriptSignal::new())
|
||||
},
|
||||
},
|
||||
};
|
||||
#[derive(Default)]
|
||||
pub struct InstanceValueStore{
|
||||
values:HashMap<Ref,
|
||||
HashMap<&'static str,
|
||||
mlua::AnyUserData
|
||||
>
|
||||
>,
|
||||
}
|
||||
pub struct InstanceValues<'a>{
|
||||
named_values:&'static phf::Map<&'static str,CreateUserData>,
|
||||
values:&'a mut HashMap<&'static str,mlua::AnyUserData>,
|
||||
}
|
||||
impl InstanceValueStore{
|
||||
pub fn get_or_create_instance_values(&mut self,instance:&rbx_dom_weak::Instance)->Option<InstanceValues>{
|
||||
LAZY_USER_DATA.get(instance.class.as_str())
|
||||
.map(|named_values|
|
||||
InstanceValues{
|
||||
named_values,
|
||||
values:self.values.entry(instance.referent())
|
||||
.or_insert_with(||HashMap::new()),
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
impl InstanceValues<'_>{
|
||||
pub fn get_or_create_value(&mut self,lua:&mlua::Lua,index:&str)->mlua::Result<Option<mlua::AnyUserData>>{
|
||||
Ok(match self.named_values.get_entry(index){
|
||||
Some((&static_index_str,&function_pointer))=>Some(
|
||||
match self.values.entry(static_index_str){
|
||||
Entry::Occupied(entry)=>entry.get().clone(),
|
||||
Entry::Vacant(entry)=>entry.insert(
|
||||
function_pointer(lua)?
|
||||
).clone(),
|
||||
}
|
||||
),
|
||||
None=>None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn instance_value_store_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut InstanceValueStore)->mlua::Result<T>)->mlua::Result<T>{
|
||||
let mut cf=lua.app_data_mut::<InstanceValueStore>().ok_or_else(||mlua::Error::runtime("InstanceValueStore missing"))?;
|
||||
f(&mut *cf)
|
||||
}
|
2
src/runner/instance/mod.rs
Normal file
2
src/runner/instance/mod.rs
Normal file
@ -0,0 +1,2 @@
|
||||
pub mod instance;
|
||||
pub use instance::Instance;
|
@ -7,7 +7,8 @@ mod color3;
|
||||
mod cframe;
|
||||
mod vector3;
|
||||
pub mod instance;
|
||||
mod number_sequence;
|
||||
mod script_signal;
|
||||
mod color_sequence;
|
||||
mod number_sequence;
|
||||
|
||||
pub use runner::{Runner,Runnable,Error};
|
||||
|
@ -37,10 +37,12 @@ fn init(lua:&mlua::Lua)->mlua::Result<()>{
|
||||
super::color3::set_globals(lua,&globals)?;
|
||||
super::vector3::set_globals(lua,&globals)?;
|
||||
super::cframe::set_globals(lua,&globals)?;
|
||||
super::instance::set_globals(lua,&globals)?;
|
||||
super::instance::instance::set_globals(lua,&globals)?;
|
||||
super::number_sequence::set_globals(lua,&globals)?;
|
||||
super::color_sequence::set_globals(lua,&globals)?;
|
||||
|
||||
lua.register_userdata_type::<super::script_signal::ScriptSignal>(mlua::UserData::register)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -88,7 +90,7 @@ impl Runnable<'_>{
|
||||
}
|
||||
}
|
||||
pub fn run_script(&self,script:super::instance::Instance)->Result<(),Error>{
|
||||
let (name,source)=super::instance::get_name_source(&self.lua,script).map_err(Error::RustLua)?;
|
||||
let (name,source)=super::instance::instance::get_name_source(&self.lua,script).map_err(Error::RustLua)?;
|
||||
self.lua.globals().raw_set("script",script).map_err(Error::RustLua)?;
|
||||
let f=self.lua.load(source.as_str())
|
||||
.set_name(name).into_function().map_err(Error::RustLua)?;
|
||||
@ -120,4 +122,23 @@ impl Runnable<'_>{
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(feature="run-service")]
|
||||
pub fn run_service_step(&self)->Result<(),mlua::Error>{
|
||||
let render_stepped=super::instance::instance::dom_mut(&self.lua,|dom|{
|
||||
let run_service=super::instance::instance::find_first_child_of_class(dom,dom.root(),"RunService").ok_or_else(||mlua::Error::runtime("RunService missing"))?;
|
||||
super::instance::instance::instance_value_store_mut(&self.lua,|instance_value_store|{
|
||||
//unwrap because I trust my find_first_child_of_class function to
|
||||
let mut instance_values=instance_value_store.get_or_create_instance_values(run_service).ok_or_else(||mlua::Error::runtime("RunService InstanceValues missing"))?;
|
||||
let render_stepped=instance_values.get_or_create_value(&self.lua,"RenderStepped")?;
|
||||
//let stepped=instance_values.get_or_create_value(&self.lua,"Stepped")?;
|
||||
//let heartbeat=instance_values.get_or_create_value(&self.lua,"Heartbeat")?;
|
||||
Ok(render_stepped)
|
||||
})
|
||||
})?;
|
||||
if let Some(render_stepped)=render_stepped{
|
||||
let signal:&super::script_signal::ScriptSignal=&*render_stepped.borrow()?;
|
||||
signal.fire(mlua::MultiValue::new());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
138
src/runner/script_signal.rs
Normal file
138
src/runner/script_signal.rs
Normal file
@ -0,0 +1,138 @@
|
||||
use std::{cell::RefCell,rc::Rc};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FunctionList{
|
||||
functions:Vec<mlua::Function>,
|
||||
}
|
||||
impl FunctionList{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
functions:Vec::new(),
|
||||
}
|
||||
}
|
||||
// This eats the Lua error
|
||||
pub fn fire(self,args:&mlua::MultiValue){
|
||||
// Make a copy of the list in case Lua attempts to modify it during the loop
|
||||
for function in self.functions{
|
||||
//wee let's allocate for our function calls
|
||||
if let Err(e)=function.call::<mlua::MultiValue>(args.clone()){
|
||||
println!("Script Signal Error: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct RcFunctionList{
|
||||
functions:Rc<RefCell<FunctionList>>,
|
||||
}
|
||||
impl RcFunctionList{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
functions:Rc::new(RefCell::new(FunctionList::new())),
|
||||
}
|
||||
}
|
||||
pub fn fire(&self,args:&mlua::MultiValue){
|
||||
// Make a copy of the list in case Lua attempts to modify it during the loop
|
||||
self.functions.borrow().clone().fire(args)
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct ScriptSignal{
|
||||
// Emulate the garbage roblox api.
|
||||
// ScriptConnection should not exist.
|
||||
// :Disconnect should be a method on ScriptSignal, and this would be avoided entirely.
|
||||
callbacks:RcFunctionList,
|
||||
once:RcFunctionList,
|
||||
wait:Rc<RefCell<Vec<mlua::Thread>>>,
|
||||
}
|
||||
pub struct ScriptConnection{
|
||||
connection:RcFunctionList,
|
||||
function:mlua::Function,
|
||||
}
|
||||
impl ScriptSignal{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
callbacks:RcFunctionList::new(),
|
||||
once:RcFunctionList::new(),
|
||||
wait:Rc::new(RefCell::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
pub fn fire(&self,args:&mlua::MultiValue){
|
||||
self.callbacks.fire(args);
|
||||
//Replace the FunctionList with an empty one and drop the borrow
|
||||
let once=std::mem::replace(&mut *self.once.functions.borrow_mut(),FunctionList::new());
|
||||
once.fire(args);
|
||||
//resume threads waiting for this signal
|
||||
let threads=std::mem::replace(&mut *self.wait.borrow_mut(),Vec::new());
|
||||
for thread in threads{
|
||||
if let Err(e)=thread.resume::<mlua::MultiValue>(args.clone()){
|
||||
println!("Script Signal thread resume Error: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn connect(&self,function:mlua::Function)->ScriptConnection{
|
||||
self.callbacks.functions.borrow_mut().functions.push(function.clone());
|
||||
ScriptConnection{
|
||||
connection:self.callbacks.clone(),
|
||||
function,
|
||||
}
|
||||
}
|
||||
pub fn once(&self,function:mlua::Function)->ScriptConnection{
|
||||
self.once.functions.borrow_mut().functions.push(function.clone());
|
||||
ScriptConnection{
|
||||
connection:self.once.clone(),
|
||||
function,
|
||||
}
|
||||
}
|
||||
pub fn wait(&self,thread:mlua::Thread){
|
||||
self.wait.borrow_mut().push(thread);
|
||||
}
|
||||
}
|
||||
impl ScriptConnection{
|
||||
pub fn position(&self)->Option<usize>{
|
||||
self.connection.functions.borrow().functions.iter().position(|function|function==&self.function)
|
||||
}
|
||||
}
|
||||
|
||||
impl mlua::UserData for ScriptSignal{
|
||||
fn add_methods<M:mlua::UserDataMethods<Self>>(methods:&mut M){
|
||||
methods.add_method("Connect",|_lua,this,f:mlua::Function|
|
||||
Ok(this.connect(f))
|
||||
);
|
||||
methods.add_method("Once",|_lua,this,f:mlua::Function|
|
||||
Ok(this.once(f))
|
||||
);
|
||||
methods.add_method("Wait",|lua,this,()|
|
||||
Ok(this.wait(lua.current_thread()))
|
||||
todo!("coroutine.yield");
|
||||
);
|
||||
// Fire is not allowed to be called from Lua
|
||||
// methods.add_method("Fire",|_lua,this,args:mlua::MultiValue|
|
||||
// Ok(this.fire(args))
|
||||
// );
|
||||
}
|
||||
}
|
||||
impl mlua::FromLua for ScriptSignal{
|
||||
fn from_lua(value:mlua::Value,_lua:&mlua::Lua)->Result<Self,mlua::Error>{
|
||||
match value{
|
||||
mlua::Value::UserData(ud)=>Ok(ud.borrow::<Self>()?.clone()),
|
||||
other=>Err(mlua::Error::runtime(format!("Expected {} got {:?}",stringify!(ScriptSignal),other))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl mlua::UserData for ScriptConnection{
|
||||
fn add_fields<F:mlua::UserDataFields<Self>>(fields:&mut F){
|
||||
fields.add_field_method_get("Connected",|_,this|{
|
||||
Ok(this.position().is_some())
|
||||
});
|
||||
}
|
||||
fn add_methods<M:mlua::UserDataMethods<Self>>(methods:&mut M){
|
||||
methods.add_method("Disconnect",|_,this,_:()|{
|
||||
if let Some(index)=this.position(){
|
||||
this.connection.functions.borrow_mut().functions.remove(index);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
@ -58,7 +58,7 @@ impl Scheduler{
|
||||
}
|
||||
|
||||
pub fn scheduler_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut crate::scheduler::Scheduler)->mlua::Result<T>)->mlua::Result<T>{
|
||||
let mut scheduler=lua.app_data_mut::<crate::scheduler::Scheduler>().ok_or(mlua::Error::runtime("Scheduler missing"))?;
|
||||
let mut scheduler=lua.app_data_mut::<crate::scheduler::Scheduler>().ok_or_else(||mlua::Error::runtime("Scheduler missing"))?;
|
||||
f(&mut *scheduler)
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user