lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



Am 20.04.2014 13:51 schrieb "Peng Zhicheng" <pengzhicheng1986@gmail.com>:
>
> Hi list,
>
> I want to share some little work I have done recently, mainly for my special
> personal needs. maybe someone else would find it useful as well.
>
> short description:
>
> I use as glue logics for some native compiled modules. several functions would
> return values to the Lua side code (as userdata, of course), which would then pass
> these values to other functions as parameters.
>
> in the wrapper/binding function, to dispatch the call, I need to know which of
> the functions produced the values: they were of different types in the original
> C++ side code, but are all void pointers now.
>
> I feel I shall redesign the APIs exposed to Lua side, so as to solve the problem.
> but since the library is incrementally evoled to what it is like today, while
> the Lua side API can't be easily changed in a short time, I now use full userdata
> to distinguash the types using metatables, since all light userdata share a single
> metatable.
>
> I feel it too much overhead using the full userdata just to pass some opaque values,
> and I need to set a per-instance metatable everytime I produced that value.
> indeed, they are just some opaque values passed to Lua then back to C++. Lua code
> don't need to operate the values: no index, no call, no compare.
>
> so I imagined, how nice there be more then one type of light userdata, at least at
> the C API level.
>
> thus my first try (attached varbits.patch): (ab)use the variant bits of the type tag
> to store this extra information. I found Lua 5.2 allocates 2 bits for this purpose,
> so now I have up to 4 different (sub)types of light userdata. that's totally enough
> for my current use case.
>
> then I thought, maybe I could go one step further, thus the second patch. I added a
> secondary tag (what I called type extention, but sadlly I couldn't think out a better
> name for that. maybe subtype?) into the TValue struct, I even give each subtype of
> lightuserdata a seperate metatable.
>
> currently, the type extension (or subtype) information is only visible to the C API,
> Lua side code are not aware of the type extension information.
>
>
> best regards.

I needed four years to learn that userdata values can have individual environment tables. So you can let the metadata table be shared while using individual environment tables, storing object related data. This helps organizing structures a lot...
I hope you know about this feature. If not, it might be useful for you.

Personally, I don't know what light userdata types are good for anymore.

Eike