How to create functions for objects at runtime in rust

Godot Version



I want to dynamically create the methods of a node. E.g.

fn process(&mut self, delta: f64) {
   // Code to drop in without doing selection logic of code here because that would be too expensive to run every frame.

What I’m trying to do is convert abstract_spell_language (that I define) into methods that will run. E.g. From abstract spell language:

func on_creation:
    add_velocity(5.3, 1, 1)

func process:
    decrease_velocity(1, 1, 1)

To Rust code:

impl ICharacterBody3D for Spell {
    fn init(base: Base<CharacterBody3D>) -> Self {
        Self {
            energy: 0.0

    fn ready(&mut self) {
        // Insert code here dynamically

    fn physics_process(&mut self, delta: f64) {
        // Insert code here dynamically

The code to be inserted would already be written, like:

impl Spell {
    fn add_velocity(&mut self, velocity_x: f64, velocity_y: f64, velocity_z: f64) {
        let new_velocity = Vector3 {x: self.base().get_velocity().x + velocity_x as f32, y: self.base().get_velocity().y + velocity_y as f32, z: self.base().get_velocity().z + velocity_z as f32};

Different instances also need to have different method implementations.

To add code like that would require dynamic compiler, I’m not aware that is a rust specialty.

I think what you want is a lambda function.

Godot has a version called Callable.

1 Like

Maybe you want to create a virtual machine?