mlua icon indicating copy to clipboard operation
mlua copied to clipboard

Added a ToLua derive macro

Open ArchangelJTW opened this issue 1 year ago • 3 comments

I just made it but it seems useful so far, at least for me it is, works with most primitives so I think it's worth adding to help reduce boilerplate:

use mlua::{FromLua, Function, Lua, LuaOptions, StdLib, ToLua};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, FromLua, Clone, ToLua)] // new ToLua derive macro
struct MyType {
    x: u32,
    y: String,
}

fn main() {
    let lua = Lua::new_with(StdLib::ALL_SAFE, LuaOptions::default()).unwrap();
    

    let lua_code = r#"
        function(myType)
              print(myType.x, myType.y)
        end
    "#;


    let f: Function = lua.load(lua_code).eval().unwrap();

    let my_type = MyType {
        x: 6,
        y: "hi, from rust to lua".into()
    };

    f.call::<MyType, ()>(my_type).unwrap();

}

ArchangelJTW avatar Jul 12 '24 23:07 ArchangelJTW

I updated it to implement UserData instead of IntoLua, this works more cleanly with passing the type in and out of lua, it will use copy on rust primitives, otherwise it will clone. It could probably be updated to include field annotations of some kind in order to be more customizable and efficient. It currently creates a simple getter and setter for all the struct fields.

ArchangelJTW avatar Jul 13 '24 17:07 ArchangelJTW

Added a ToLuaTable and FromLuaTable macro, this essentially, in a way, allows you serialize and deserialize Lua tables to and from rust types.

ArchangelJTW avatar Jul 13 '24 18:07 ArchangelJTW

This would be a fantastic addition, are there any major blockers that must be addressed for this PR? I volunteer to help out if need be :)

vhyrro avatar Nov 13 '24 09:11 vhyrro