-
Hi, I'm playing around with pub struct LuaClientResponse(pub u16);
impl UserData for LuaClientResponse {
fn add_methods<'lua, M: UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method("status", |_, resp, ()| Ok(resp.0));
}
}
let fetch_json = lua.create_async_function(|_, uri: String| async move {
let resp = http_client::get(&uri).await.into_lua_err()?;
let json = resp.json::<serde_json::Value>().await.into_lua_err()?;
let status = resp.url().to_string();
// ...
// This below does not work if I implement `UserData`.
// But it does if, for example, I serialize the json payload
// via `LuaSerdeExt` and return it like `lua.to_value(&json)`.
Ok(LuaClientResponse(status))
})
lua.globals().set("fetch_json", fetch_json)?; I would like to be able to do something like this: local resp = fetch_json("http://localhost/xyz")
print(resp.status()) Is there a way to return a type with methods similar to what |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
You can return |
Beta Was this translation helpful? Give feedback.
-
It worked by calling let fetch = lua.create_async_function(|_, uri: String| async move {
let resp = http_client::get(&uri).await.into_lua_err()?;
// ...
let status = resp.status().as_u16();
Ok(LuaClientResponse(status).into_lua(lua))
}) And calling the method like this local resp = fetch("http://localhost/xyz")
print(resp:status())
-- 200 Thanks! |
Beta Was this translation helpful? Give feedback.
It worked by calling
into_lua
on the custom data type before returning it likeAnd calling the method like this
Thanks!