From c702c5eff26d3bdb371db90ebf0f79b6e152b687 Mon Sep 17 00:00:00 2001 From: Alex Orlenko Date: Mon, 21 Jun 2021 20:28:14 +0100 Subject: [PATCH] Add userdata example --- Cargo.toml | 4 ++++ examples/userdata.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 examples/userdata.rs diff --git a/Cargo.toml b/Cargo.toml index 5d7175b..2c40a2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -97,3 +97,7 @@ required-features = ["macros"] [[example]] name = "serialize" required-features = ["serialize"] + +[[example]] +name = "userdata" +required-features = ["macros"] diff --git a/examples/userdata.rs b/examples/userdata.rs new file mode 100644 index 0000000..8823dfd --- /dev/null +++ b/examples/userdata.rs @@ -0,0 +1,45 @@ +use mlua::{chunk, Lua, MetaMethod, Result, UserData}; + +#[derive(Default)] +struct Rectangle { + length: u32, + width: u32, +} + +impl UserData for Rectangle { + fn add_fields<'lua, F: mlua::UserDataFields<'lua, Self>>(fields: &mut F) { + fields.add_field_method_get("length", |_, this| Ok(this.length)); + fields.add_field_method_set("length", |_, this, val| { + this.length = val; + Ok(()) + }); + fields.add_field_method_get("width", |_, this| Ok(this.width)); + fields.add_field_method_set("width", |_, this, val| { + this.width = val; + Ok(()) + }); + } + + fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_method("area", |_, this, ()| Ok(this.length * this.width)); + methods.add_method("diagonal", |_, this, ()| { + Ok((this.length.pow(2) as f64 + this.width.pow(2) as f64).sqrt()) + }); + + // Constructor + methods.add_meta_function(MetaMethod::Call, |_, ()| Ok(Rectangle::default())); + } +} + +fn main() -> Result<()> { + let lua = Lua::new(); + let rectangle = Rectangle::default(); + lua.load(chunk! { + local rect = $rectangle() + rect.width = 10 + rect.length = 5 + assert(rect:area() == 50) + assert(rect:diagonal() - 11.1803 < 0.0001) + }) + .exec() +}