Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use bevy_mod_scripting_world::{ThreadWorldContainer, WorldGuard};
use bevy_platform::collections::HashMap;
use bevy_reflect::{Reflect, TypeInfo};
use parking_lot::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::any::TypeId;
use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::collections::VecDeque;
use std::hash::Hash;
Expand Down Expand Up @@ -144,6 +144,9 @@ pub struct DynamicScriptFunction {
func: Arc<
dyn Fn(FunctionCallContext, VecDeque<ScriptValue>) -> ScriptValue + Send + Sync + 'static,
>,
/// The script's own function this one calls, see [`DynamicScriptFunction::with_script_function`]
#[debug_with_type_info(skip)]
script_function: Option<Arc<dyn Any + Send + Sync>>,
}

#[derive(Reflect, Clone, DebugWithTypeInfo)]
Expand Down Expand Up @@ -254,12 +257,26 @@ impl DynamicScriptFunction {
bound
}

/// Records the script's own function (i.e. a Lua function) this function calls.
///
/// The language can then hand that function back to the script as it is, instead of wrapping this one.
pub fn with_script_function(mut self, function: Arc<dyn Any + Send + Sync>) -> Self {
self.script_function = Some(function);
self
}

/// The script's own function this function calls, if it was made from one of type `T`.
pub fn script_function<T: Any>(&self) -> Option<&T> {
self.script_function.as_deref()?.downcast_ref()
}

/// Fixes the first argument of the function, i.e. a receiver or a type.
///
/// The returned function is called with the remaining arguments. Its info is unchanged.
pub fn curry(&self, first: ScriptValue) -> Self {
let inner = self.func.clone();
DynamicScriptFunction {
script_function: None,
info: self.info.clone(),
func: Arc::new(move |context, mut args| {
args.push_front(first.clone());
Expand Down Expand Up @@ -337,6 +354,7 @@ where
.with_name(std::any::type_name::<F>())
.into(),
func: Arc::new(fn_),
script_function: None,
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::{
collections::VecDeque,
ops::{Deref, DerefMut},
os::raw::c_int,
sync::Arc,
};

use bevy_mod_scripting_asset::Language;
Expand Down Expand Up @@ -211,15 +212,22 @@ fn non_table_value(value: Value) -> mlua::Result<ScriptValue> {
Value::Integer(i) => ScriptValue::Integer(i),
Value::Number(n) => ScriptValue::Float(n),
Value::String(s) => ScriptValue::String(s.to_str()?.to_owned().into()),
Value::Function(f) => ScriptValue::Function(
(move |_context: FunctionCallContext, args: VecDeque<ScriptValue>| {
match f.call::<MultiLuaScriptValue>(MultiLuaScriptValue(args)) {
Ok(v) => v.into_script_value(),
Err(e) => ScriptValue::Error(InteropError::external(Box::new(e))),
}
})
.into(),
),
Value::Function(f) => {
// kept next to the function calling it, to hand it back to Lua as it is, see `IntoLua`
let f = Arc::new(f);
let called = f.clone();
ScriptValue::Function(
DynamicScriptFunction::from(
move |_context: FunctionCallContext, args: VecDeque<ScriptValue>| {
match called.call::<MultiLuaScriptValue>(MultiLuaScriptValue(args)) {
Ok(v) => v.into_script_value(),
Err(e) => ScriptValue::Error(InteropError::external(Box::new(e))),
}
},
)
.with_script_function(f),
)
}
// Value::Thread(thread) => todo!(),
Value::UserData(ud) => {
if let Ok(type_ref) = ud.borrow::<LuaTypeRef>() {
Expand Down Expand Up @@ -550,11 +558,16 @@ impl IntoLua for LuaScriptValue {
ScriptValue::Reference(r) => LuaReflectReference::from(r).into_lua(lua)?,
ScriptValue::Type(type_id) => LuaTypeRef(type_id).into_lua(lua)?,
ScriptValue::Error(script_error) => return Err(mlua::Error::external(script_error)),
ScriptValue::Function(function) => lua
.create_function(move |lua, args: MultiLuaScriptValue| {
call_from_lua(lua, |context| function.call(args.0, context))
})?
.into_lua(lua)?,
ScriptValue::Function(function) => match function.script_function::<mlua::Function>() {
// a function of this Lua state is handed back as it is: the script gets the function it
// passed in, and calls it without going through Rust
Some(f) if *f.weak_lua() == lua.weak() => Value::Function(f.clone()),
_ => lua
.create_function(move |lua, args: MultiLuaScriptValue| {
call_from_lua(lua, |context| function.call(args.0, context))
})?
.into_lua(lua)?,
},
ScriptValue::FunctionMut(function) => lua
.create_function(move |lua, args: MultiLuaScriptValue| {
call_from_lua(lua, |context| function.call(args.0, context))
Expand Down Expand Up @@ -737,5 +750,13 @@ mod test {
assert_eq!(from_stack.len(), 1);
assert_eq!(canonical(&from_stack[0]), canonical(&from_value));
}
// functions come back to their Lua state as themselves, and wrapped to another
let function = Value::Function(lua.create_function(|_, ()| Ok(())).unwrap());
let converted = LuaScriptValue::from_lua(function.clone(), &lua).unwrap().0;
let back = LuaScriptValue(converted.clone()).into_lua(&lua).unwrap();
assert_eq!(back, function);
let other = mlua::Lua::new();
let wrapped = LuaScriptValue(converted).into_lua(&other).unwrap();
assert!(wrapped.is_function());
}
}
Loading