bevy_scriptum/book/src/javascript/calling_script_from_rust.md
Jaroslaw Konik 36cc907f0e
Some checks failed
Book / test (pull_request) Has been cancelled
Rust / build (3.4.4, map[os:ubuntu-latest]) (pull_request) Has been cancelled
Implement JavaScript runtime
2026-06-04 23:50:53 +02:00

1.8 KiB

Calling JavaScript from Rust

To call a function defined in JavaScript

function on_update() {
}

We need to acquire the JsRuntime resource within a bevy system. Then we will be able to call call_fn on it, providing the name of the function to call, the JsScriptData that has been automatically attached to the entity after an entity with a script attached has been spawned and its script evaluated, the entity and optionally some arguments.

# extern crate bevy;
# extern crate bevy_scriptum;

use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::javascript::prelude::*;

fn call_js_on_update_from_rust(
    mut scripted_entities: Query<(Entity, &mut JsScriptData)>,
    scripting_runtime: ResMut<JsRuntime>,
) {
    for (entity, mut script_data) in &mut scripted_entities {
        // calling function named `on_update` defined in JavaScript script
        scripting_runtime
            .call_fn("on_update", &mut script_data, entity, ())
            .unwrap();
    }
}

We can also pass some arguments by providing a tuple or Vec as the last call_fn argument.

# extern crate bevy;
# extern crate bevy_scriptum;

use bevy::prelude::*;
use bevy_scriptum::prelude::*;
use bevy_scriptum::runtimes::javascript::prelude::*;

fn call_js_on_update_from_rust(
    mut scripted_entities: Query<(Entity, &mut JsScriptData)>,
    scripting_runtime: ResMut<JsRuntime>,
) {
    for (entity, mut script_data) in &mut scripted_entities {
        scripting_runtime
            .call_fn("on_update", &mut script_data, entity, (123, String::from("hello")))
            .unwrap();
    }
}

They will be passed to the on_update JavaScript function

function on_update(a, b) {
    print(a); // 123
    print(b); // hello
}