Skip to content

Calling methods on userdata? #173

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

Closed
jugglerchris opened this issue Apr 26, 2020 · 2 comments
Closed

Calling methods on userdata? #173

jugglerchris opened this issue Apr 26, 2020 · 2 comments

Comments

@jugglerchris
Copy link
Collaborator

I realise it's not a great time to be asking a question give #172...

Is there a way to call a method on a UserData (or indeed a Table, or general Value) from Rust?

My use case is that I want to wrap several Rust types as UserData, which all implement the same trait. In some places I want to be able to pass any of the concrete types from Lua to a Rust function, which only cares that it implements the trait.

In my home-grown bindings I implemented this by adding as_<TRAIT> methods I can call without knowing the type, which returned something like an Rc<RefCell<dyn TRAIT>> which I could then use.

@kyren
Copy link
Contributor

kyren commented Apr 27, 2020

You can definitely call a method on a table manually by getting the function from the table, then passing the table as the first argument of the function call. It would be nice if there was a better shortcut for doing that.

This is not as easy on userdata, as there's no way currently of calling lua_gettable on a userdata directly, so you can't get a handle to a userdata method directly. However you can always go through Lua to do things like this, so you could just exec lua code to return a handle to that function and then call it like any other function (with the correct AnyUserData as the first argument).

You could make the case that most of the methods from Table should also be available on AnyUserData.

@jugglerchris
Copy link
Collaborator Author

Thanks - I think calling a Lua function will do the trick nicely in this case.
I'd maybe go slightly further than adding most of the Table methods to AnyUserData - Function::call should be available on both (and/or Value) since they can be made callable with the right metamethods.

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