Replies: 1 comment
-
|
For anyone still looking for an answer to this like I was, I found a relatively straight forward way to do this for non- // main.rs -- assume Name is an external type
pub struct Name {
pub name: String,
}
impl Name {
pub const fn new(name: String) -> Self { Self { name } }
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.name.fmt(f) }
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let lua = Lua::new();
// calling `register_userdata_type::<T>(...)` is roughly equivalent to `impl UserData for T`
lua.register_userdata_type::<Name>(|reg| {
reg.add_field_method_get("name", |lua, this| Ok(this.name.as_str().into_lua(lua)?));
reg.add_field_method_set("name", |_, this, val| { this.name = val; Ok(()) });
reg.add_meta_function(LuaMetaMethod::ToString, |_, this: LuaUserDataRef<Name>| Ok(format!("{:?}", this)));
})?;
lua.globals().set("Name", lua.create_function(|lua, name| {
let n = if let Some(name) = name { Name::new(name) } else { Name::default() };
lua.create_any_userdata(n)
})?)?;
Ok(())
}-- script.lua
local n1 = Name("foo");
print("typeof(n1):", n1);
print("n1:", n1);
print("n1.name:", n1.name);
local n2 = Name();
print("n2:", n2);
n2.name = "bar";
print("n2:", n2);Results in: typeof(n1): Name
n1: "foo"
n1.name: "foo"
n2: ""
n2: "bar" |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I'm currently having the following problem: I have external dependent types, something like:
from an external crate.
I now want to bind Mat3 into the Lua context. To do this I (have to) use the rust "newtype" pattern, so:
and implement the
UserDatafor those.If I now, however, write an accessor for one of the axis for Lua, I have to wrap the resulting Value in my crate-local files. This leads (because of the ownership) to a copied Object in Lua and if I edit that, the original axis (obviously) doesn't get changed...
The only 2 options I see to circumvent this is to, either reimplement these types in my crate (not something I'm very keen on) or modify the original (glam) crate to have all the external types implement
UserData.Is there something I'm missing, i.e. a way to circumvent the orphan rules that gives me the ability to retain ownership of the object with
Mat3? Or implementingUserDatafor the references? Or have a reference wrapper (how would that work?)?Your help would be much appreciated.
Beta Was this translation helpful? Give feedback.
All reactions