Skip to content

perf: hand Lua functions back to Lua as they are - #721

Closed
makspll wants to merge 3 commits into
agent/lua-stack-conversionfrom
agent/lua-function-round-trip
Closed

makspll wants to merge 3 commits into
agent/lua-stack-conversionfrom
agent/lua-function-round-trip

Conversation

@makspll

@makspll makspll commented Nov 13, 2026

Copy link
Copy Markdown
Owner

A Lua function converted to a ScriptValue and back was wrapped in a new Rust callback every time: the script got a different function than the one it passed in, and calling it went Lua → Rust → Lua.

DynamicScriptFunction can now record the script's own function it calls (with_script_function / script_function::<T>()). The Lua backend stores the mlua::Function there and hands it back as it is when the value returns to the same Lua state (compared by WeakLua), any other state still gets a wrapper. Curried functions don't keep it.

local f = function() end
assert(some_rust_fn_returning_its_argument(f) == f) -- was false

Stacked on #720 (same file).

Measured on the reactive ui stack (#719 + #720 + this, prebuilt binaries, alternating rounds), where component props holding handlers go to Rust and back:

bench #719 + #720 + this PR
inventory select Closures 22.9 µs 22.1 µs (−4%)
inventory select Paths 20.2 µs 18.8 µs (−7%)
inventory mount or unmount 200 Closures (8 rounds) 2.05 ms 2.04 ms

Mounting doesn't change: creating the wrapper was a small part of a slot. Handlers called from Lua get cheaper.

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.
@makspll
makspll added this pull request to stack #722 November 13, 2026 08:45
@semanticdiff-com

semanticdiff-com Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Review changes with  SemanticDiff

Changed Files
File Status
  crates/languages/bevy_mod_scripting_lua/src/bindings/script_value.rs  60% smaller
  crates/bevy_mod_scripting_bindings/src/function/script_function.rs  4% smaller

@makspll makspll closed this Nov 14, 2026
An error occurred while trying to automatically change base from agent/lua-stack-conversion to main November 14, 2026 16:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant