add example

This commit is contained in:
Jaroslaw Konik 2025-05-24 12:12:43 +02:00
parent 1467fa3bba
commit 21828eea8d
4 changed files with 54 additions and 3 deletions

View file

@ -185,6 +185,12 @@ name = "function_params_ruby"
path = "examples/ruby/function_params.rs"
required-features = ["ruby"]
[[example]]
name = "function_return_value_ruby"
path = "examples/ruby/function_return_value.rs"
required-features = ["ruby"]
[dev-dependencies]
tracing-subscriber = "0.3.18"
mlua = { version = "0.9.8", features = ["luajit", "vendored", "send"] }

View file

@ -0,0 +1,3 @@
def get_value
42
end

View file

@ -0,0 +1,42 @@
use bevy::{app::AppExit, prelude::*};
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::ruby::prelude::*;
use magnus::value::InnerValue;
use magnus::TryConvert;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, startup)
.add_systems(Update, call_lua_on_update_from_rust)
.add_scripting::<RubyRuntime>(|runtime| {
runtime.add_function(String::from("quit"), |mut exit: EventWriter<AppExit>| {
exit.write(AppExit::Success);
});
})
.run();
}
fn startup(mut commands: Commands, assets_server: Res<AssetServer>) {
commands.spawn(Script::<RubyScript>::new(
assets_server.load("examples/ruby/function_return_value.rb"),
));
}
fn call_lua_on_update_from_rust(
mut scripted_entities: Query<(Entity, &mut RubyScriptData)>,
scripting_runtime: ResMut<RubyRuntime>,
mut exit: EventWriter<AppExit>,
) {
for (entity, mut script_data) in &mut scripted_entities {
let val = scripting_runtime
.call_fn("get_value", &mut script_data, entity, ())
.unwrap()
.0;
scripting_runtime.with_engine_thread(move |ruby| {
let val: i32 = TryConvert::try_convert(val.get_inner_with(&ruby)).unwrap();
println!("script returned: {}", val);
});
exit.write(AppExit::Success);
}
}

View file

@ -275,7 +275,7 @@ impl Drop for RubyRuntime {
}
#[derive(Clone)]
pub struct RubyValue(magnus::value::Opaque<magnus::Value>);
pub struct RubyValue(pub magnus::value::Opaque<magnus::Value>);
impl RubyValue {
fn nil(ruby: &Ruby) -> Self {
@ -339,11 +339,11 @@ impl Runtime for RubyRuntime {
}
fn with_engine_mut<T>(&mut self, _f: impl FnOnce(&mut Self::RawEngine) -> T) -> T {
unimplemented!();
unimplemented!("Ruby requires single threaded execution, use `with_engine_thread`");
}
fn with_engine<T>(&self, _f: impl FnOnce(&Self::RawEngine) -> T) -> T {
unimplemented!();
unimplemented!("Ruby requires single threaded execution, use `with_engine_thread`");
}
fn eval(