Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Push mutable reference to variable to script #294

Open
konceptosociala opened this issue Jul 25, 2023 · 1 comment
Open

Push mutable reference to variable to script #294

konceptosociala opened this issue Jul 25, 2023 · 1 comment

Comments

@konceptosociala
Copy link

I can capture rust variable with chunk! macro like

let name = "Rustacean";
lua.load(chunk! {
    print("hello, " .. $name)
}).exec()

But what if I have external script inside a file script.lua, is it able to capture rust mutable reference to Lua?

@konceptosociala
Copy link
Author

My proximate solution is like

main.rs:

use std::{path::Path, fmt::Display};

use mlua::{Lua, UserData};

#[derive(Clone)]
struct MyStruct(i32);

impl Display for MyStruct {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl UserData for MyStruct {
    fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) {
        fields.add_field_method_get("val", |_, this| {
            Ok(this.0)
        });
    }

    fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
        methods.add_method_mut("add", |_, this, value: i32| {
            this.0 += value;
            Ok(())
        });
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let lua = Lua::new();
    let mut my_struct = MyStruct(12);

    for _ in 0..5 {
        lua.globals().set("MyStruct", my_struct)?;
        lua.load(Path::new("script.lua")).exec()?;
        my_struct = lua.globals().get::<&str, MyStruct>("MyStruct")?;
    }

    Ok(())
}

script.lua:

local my_struct = MyStruct;

print("Old value: ", my_struct.val)
my_struct:add(15)
print("New value: ", my_struct.val)

Output:

Old value: 	12
New value: 	27
Old value: 	27
New value: 	42
Old value: 	42
New value: 	57
Old value: 	57
New value: 	72
Old value: 	72
New value: 	87

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

No branches or pull requests

1 participant