lua-users home
lua-l archive

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


Am 29.04.2014 01:59 schröbte William Ahern:
On Sun, Apr 27, 2014 at 08:09:10AM +0200, Karel Tuma wrote:
Hello,

Just stumbled on this again (and thus have to run modified Lua),
so I guess it's worth it to generalize this into a polyfill for portability.

https://github.com/katlogic/pudata

Sometimes, one needs to push existing userdata by pointer. This is not
safe (as the pointer might be stale), therefore it is not part of core
Lua api.

I don't understand what the issue is. Can you describe it in more detail?
Why would you push a stale pointer? A pointer is completely and utterly
invalid after it's been freed, so even copying its value is invalid, as well
as dereferencing it.


This type of function is useful for certain types of userdata, e.g. singletons, structs in structs, and value types. If you want to push the pointer to a singleton or to a sub-element of a struct to your Lua code, you can wrap that pointer in a full userdata with a metatable, or reuse an already existing userdata that wraps the same pointer. The same principle works for enums and flags, but a single global cache is not sufficient in that case, every enum type needs its own. Since this type of caching isn't useful for most userdata I wouldn't monkey-patch `lua_newuserdata` but use an extra function instead. This way you can also provide an index where to store/lookup the cache (e.g. the registry for a single global cache, or a metatable for a per-type cache).


Philipp