#help with creating an mlua api to spawn a cube

1 messages · Page 1 of 1 (latest)

last glade
#
use bevy::prelude::*;
use mlua::prelude::*;

fn main() {
    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, run_lua)
        .run();
}

fn newObject(_: &Lua, type: String) -> LuaResult<()> {
    commands.spawn((
        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
        MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
        Transform::from_xyz(0.0, 0.5, 0.0),
    ));
    Ok(())
}

fn run_lua(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let lua = Lua::new();

    lua.globals()
        .set("create_new", lua.create_function(newObject).unwrap())
        .unwrap();
    lua.load(std::fs::read_to_string("./test.lua").unwrap())
        .exec()
        .unwrap();
}

I want to be able to do something like this, but I have no idea how to access commands, meshes and materials from within the newObject function. (I'm new to both Rust and Bevy. If you reply, please explain as well as possible so that I can understand)
Any help is appreciated!

somber chasm
#

write the cubes to a global table and read from that table after the execution

fn run_lua(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let lua = Lua::new();

    lua.globals()
        // i don't know the correct name for here
        .set("cubes", lua.create_table().unwrap())
        .unwrap();
    lua.load(std::fs::read_to_string("./test.lua").unwrap())
        .exec()
        .unwrap();
    // i don't know the correct name for here
    for cube in lua.get_global("cubes") {
      commands.spawn((
        Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
        MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
        Transform::from_xyz(0.0, 0.5, 0.0),
      ));
    }
}
last glade
somber chasm
#

commands are deferred anyway

#

so you wouldn't be able to manipulate an entity created with Commands until next frame

last glade
somber chasm
#

it is not really next frame, but next checkpoint, but it is still in a different system from the one where it was called

last glade
somber chasm
#

it would need to be 2 different systems

#

or create already on the moved position