|
On 21/04/2014 4:40 PM, Peng Zhicheng wrote:
I just feel the current two userdata types are either `too light' or `too heavy' it might be an interesting idea to have something inbetween.
Hi Peng,I just wanted to add my support to your idea. Thanks for the patches. I think that what you are proposing is a useful idea. If a similar mechanism was available as part of Lua core I would use it.
The problem for me with light userdata is that they are typeless (like a void pointer in C). There is no built-in way for either Lua nor C to associate a type with the pointer. This becomes a problem as soon as light user data is used for two distinct purposes in the code.
Use cases for type-ids for light user data include:- type checking for correctness, safety and/or sanity. i.e. validating that a light user data refers to a particular type of thing. To me this is the main use-case.
- polymorphic dispatch (dispatch in Lua *or C* based on the type of the light user data). People will always argue that you should use heavy user data for this, but if you can use light user data I think it has obvious benefits. Especially for user defined data types that have value semantics.
It seems desirable to bind the user data type-id in the Lua value somehow. Obvious alternatives are: indirection via "ids" that encode both the type and a pointer/index to the real object (this is not free or trivial to implement in C), or to encode the type in the C pointer (you probably have at least the 2 MSB spare due to 4-byte alignment, and a lot of LSBs spare on 64 bit systems).
All that said, I'm not sure whether it warrants adding time or space overhead to existing Lua data structures. It seems like it would only be justified if it soaks up spare bits, not if makes existing data structures bigger.
Just my two cents, Ross.