From 6b990c33db877c51a6c6429a7315ccb0ac9312d9 Mon Sep 17 00:00:00 2001 From: makspll Date: Fri, 13 Nov 2026 08:22:00 +0000 Subject: [PATCH 1/2] perf: hand Lua functions back to Lua as they are A Lua function converted to a script value and back was wrapped in a new Rust callback each time: calling it went Lua -> Rust -> Lua, and it was not equal to the function passed in. --- .../src/function/script_function.rs | 20 +++++++- .../src/bindings/script_value.rs | 49 +++++++++++++------ 2 files changed, 54 insertions(+), 15 deletions(-) diff --git a/crates/bevy_mod_scripting_bindings/src/function/script_function.rs b/crates/bevy_mod_scripting_bindings/src/function/script_function.rs index 44939abf47..fc0c6c679a 100644 --- a/crates/bevy_mod_scripting_bindings/src/function/script_function.rs +++ b/crates/bevy_mod_scripting_bindings/src/function/script_function.rs @@ -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; @@ -144,6 +144,9 @@ pub struct DynamicScriptFunction { func: Arc< dyn Fn(FunctionCallContext, VecDeque) -> 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>, } #[derive(Reflect, Clone, DebugWithTypeInfo)] @@ -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) -> 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(&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()); @@ -337,6 +354,7 @@ where .with_name(std::any::type_name::()) .into(), func: Arc::new(fn_), + script_function: None, } } } diff --git a/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs b/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs index a6cbca44c6..0067481bcc 100644 --- a/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs +++ b/crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs @@ -3,6 +3,7 @@ use std::{ collections::VecDeque, ops::{Deref, DerefMut}, os::raw::c_int, + sync::Arc, }; use bevy_mod_scripting_asset::Language; @@ -211,15 +212,22 @@ fn non_table_value(value: Value) -> mlua::Result { 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| { - match f.call::(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| { + match called.call::(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::() { @@ -485,11 +493,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::() { + // 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)) @@ -672,5 +685,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()); } } From 4107832f6650573ca1caddda97655819cb15c599 Mon Sep 17 00:00:00 2001 From: makspll Date: Fri, 13 Nov 2026 10:26:24 +0000 Subject: [PATCH 2/2] chore: rerun CI