2

The documentation for lua_newuserdatauv(lua_State *L, size_t size, int nuvalue) says

This function creates and pushes on the stack a new full userdata, with nuvalue associated Lua values, called user values, plus an associated block of raw memory with size bytes.

The "block of raw memory" part seems clear: I allocate a block of memory of determined size (of some struct, for example), then do whatever I want with it. But what exactly are the "user values"?

The second part of documentation says

The user values can be set and read with the functions lua_setiuservalue and lua_getiuservalue.

Does it mean that userdata basically allocates an additional array of these user values? What are these user values exactly? How are they different from basic Lua types and how their usage is different from these basic types?

The manual does not give much information about these user values and the 4th edition of "Programming on Lua" says that any userdata can have one single value associated with it and in Lua 5.2 it must be a table, which actually makes sense, but it looks like all this information is outdated.

ESkri
  • 1,461
  • 1
  • 1
  • 8
Sun of A beach
  • 171
  • 1
  • 10

1 Answers1

2

The "block of raw memory" part seems clear: I allocate a block of memory of determined size

Not you.
Lua is the owner of this memory block.
Lua allocates it, and Lua will deallocate it automatically as usual GC object.

do whatever I want with it

Not "whatever".
Only read, write and pass as parameter.

But what exactly are the "user values"?

User value is a slot for storing arbitrary Lua value.

Does it mean that userdata basically allocates an additional array of these user values?

Yes

What are these user values exactly?
How are they different from basic Lua types?

User value is not a data type.
It is a private variable created for your userdata.
Variables in Lua can hold any Lua value.
It is up to you to decide what you want to store in them and how many of them you need.
You may create 0 user values.

ESkri
  • 1,461
  • 1
  • 1
  • 8
  • This question is kinda opinion-based but what these user values are used for? I mean its possible to allocate memory for additional values by increasing `size` parameter. Is there something unique about user values that makes them more suitable for some applications? – Sun of A beach Feb 03 '23 at 21:14
  • 1
    `size` parameter is the room for storing C variables, `nuvalue` - for storing Lua variables. Sometimes userdata should be able to access some Lua values, for example, globals table (`_G`), or Lua upvalues shared between all userdata methods. – ESkri Feb 04 '23 at 09:58