lua-users home
lua-l archive

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


On 22/2/22 16:13, 云风 Cloud Wu wrote:
Lightuserdata is a value and all the lightuserdata share the same one metatable.

I think more lightuserdata type with independent metatable would be
helpful. I suggest changing some C APIs like these :

// Push a C pointer with type, returns a unique typeid (Not zero)
associated with this type.
int lua_pushlightuserdata(lua_State *L, void *p, const char *typename);

// Returns typeid if the value at the given index is a light userdata,
and 0 otherwise.
int lua_islightuserdata(lua_State *L, int index);

If we call lua_setmetatable with a  lightuserdata, the metatable of
different types are independent.

The total numbers of  types don't need to much, 64K (even 256) would
be a reasonable number, and it can be easily encoded in TValue struct.

--
http://blog.codingnow.com


I don't see the need, and I think it makes things less interoperable.

To get similar functionality, all you really need is a "cache" when pushing pointers of the same type. You can create this cache as a table in the lua registry; I've frequently stored it at static symbol's address. For lookup with `lua_rawgetp`. e.g. in luaossl: https://github.com/wahern/luaossl/blob/1054d12f23ecd177881b1bcb6ade92f247cc01e9/src/openssl.c#L9125 i.e. you have the storage of: `REGISTRY[lightuserdata_of_globalsymbol][lightuserdata_of_pointer] = fulluserdata` Note that you should make `REGISTRY[lightuserdata_of_globalsymbol]` a weak table. See https://github.com/wahern/luaossl/blob/1054d12f23ecd177881b1bcb6ade92f247cc01e9/src/openssl.c#L13044-L13054 for an example.


Your proposal would make things less interoperable, as libraries would need to coordinate on the indexes: e.g. library A might hard-code 10,11,12. library B might hard-code 12,13,14.

One solution to this is to use something that is guaranteed unique at runtime. If you had a ssize_t to do so you could use an address (which has additional optimizations via the linker); but if you only have a space of 64K or 256 then you need some registry.... and now if you squint hard enough you have what I recommend above.