Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't save LuaFunction #62

Closed
rise0chen opened this issue Jul 8, 2021 · 4 comments
Closed

Can't save LuaFunction #62

rise0chen opened this issue Jul 8, 2021 · 4 comments

Comments

@rise0chen
Copy link
Contributor

rise0chen commented Jul 8, 2021

struct Uart<'lua> {
    on_message: LuaFunction<'lua>,
}
impl<'lua> LuaUserData for Uart<'lua> {}


    let exports = lua.create_table()?;
    lua.create_userdata(Uart {
        on_message: lua.create_function(|_, msg: String| Ok(()))?,
    });
    pub fn create_userdata<T>(&self, data: T) -> Result<AnyUserData>
    where
        T: 'static + MaybeSend + UserData,
    {
        unsafe { self.make_userdata(UserDataCell::new(data)) }
    }

I think, create_userdata just need 'lua. Why require 'static?

@khvzak
Copy link
Member

khvzak commented Jul 9, 2021

UserData needs 'static due to TypeId::of::<T> requirements.
TypeId is used for generating and attaching shared metatable to UserData.

As an alternative, you could use Scope::create_nonstatic_userdata, it does not have 'static requirements and as a tradeoff uses unique metatable per instance (which is less efficient).

@rise0chen
Copy link
Contributor Author

let uart = lua.scope(|scope| {
    scope.create_nonstatic_userdata(Uart {
        on_message: lua.create_function(|_, msg: String| Ok(()))?,
    })
})?;
pub fn scope<'lua, 'scope, R, F>(&'lua self, f: F) -> Result<R>
where
    'lua: 'scope,
    R: 'static,
    F: FnOnce<(&Scope<'lua, 'scope>,), Output = Result<R>>,

Oh no, Result<R>> require 'static.

@khvzak
Copy link
Member

khvzak commented Jul 9, 2021

This is how Scope works - it drops scoped objects on function leave.

  1. You could place logic inside Scope
  2. Or alternatively store Lua objects in Registry using Lua::create_registry_value and keep RegistryKey which is 'static
    You can retrieve values back using Lua::registry_value

@rise0chen
Copy link
Contributor Author

thanks, it's perfect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants