-
I'm trying to use pub struct Route<'a> {
callback: LuaFunction<'a>,
}
pub struct Router<'a>(Vec<Route<'a>>);
impl<'a> UserData for Router<'a> {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method_mut("register", Self::register);
}
}
impl<'a> Router<'a> {
fn register(
_: &Lua,
router: &mut Router<'a>,
(_, callback): (LuaValue<'a>, LuaFunction<'a>),
) -> LuaResult<()> {
router.0.push(Route {
callback,
});
Ok(())
}
} This obviously fails, due to lifetime stuff. How would I properly do this? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 11 replies
-
Could you please provide more context/full example? Your code compiles fine: let mut router = Router(Vec::new());
let f = lua.create_function(|_, ()| Ok(()))?;
Router::register(&lua, &mut router, (LuaNil, f))?; |
Beta Was this translation helpful? Give feedback.
-
Unfortunately you cannot refer to a An example using pub struct Router;
impl UserData for Router {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_function(
"register",
|lua: &Lua, (router, _, callback): (AnyUserData, LuaValue, LuaFunction)| {
// To get `router` as a Router instance:
// let router = router.borrow::<Router>()?;
let routes = match router.get_user_value::<Option<LuaTable>>()? {
Some(t) => t,
None => {
let table = lua.create_table()?;
router.set_user_value(table.clone())?;
table
}
};
let len = routes.raw_len();
routes.raw_insert(len + 1, callback)?;
Ok(())
},
);
}
} |
Beta Was this translation helpful? Give feedback.
Unfortunately you cannot refer to a
LuaFunction
in that way :(A possible solution could be storing
Vec<Route>
inside Lua (in aUserData
) and refer to it usingget_user_value()
/set_user_value()
or use Registry (vianamed_registry_value
).An example using
get/set_user_value