lua-users home
lua-l archive

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


Hi!

Am 19.08.2015 um 20:56 schröbte Tim Hill:

As I said in my earlier post, the original motivation for userdata
was to allow Lua to provide opaque storage for C libraries. The
operative word here is “opaque” .. Lua can store the data and manage
its lifetime (via the GC), but not access it. This provided a string
guarantee that the C library could rely on the integrity of the data
in the userdata when called, since Lua code could not corrupt it.

I think there's still some confusion. Let me try: Forget slice, think user-defined tag. The original userdata has tag 0, and you can push additional aliases (same pointer, different tag). Naturally, the userdata gets collected when the last reference (tags are ignored for this) vanishes. The userdata is still opaque, Lua doesn't know/care what's in it. What you *can* do as the user is to check in your (meta-)methods, which tag the userdata that was passed as argument has. E.g. if you get the original userdata (<0x1234|0>) in your `__index` metamethod, you would handle the keys "x" (pushing/returning a number) and "y" (pushing/returning the userdata with alias number 1: <0x1234|1>). If the alias number is 1, you'd handle the "z" key (pushing/returning a string). This would roughly correspond to the following C struct:

    struct {
      double x;
      struct {
        char const* z;
      } y;
    } ud;


No lifetime issues for dependent userdata and no additional memory allocations, because there *is* only one userdata.

You could also use this mechanism to implement immutable userdata references: tag 0 is normal/mutable, but if the mutating (meta-)methods are called on a userdata with tag 1, they could raise an error.

I'm starting to like it (given that you can really use the extra bits from the type tag in the TValue for the user-defined tag values).


What you are asking for is transparent userdata; that is a block of userdata that can be processed by Lua code. There are several different approaches to this:

I don't think that's what the OP is asking for ...


—Tim


Philipp