Home > Enterprise >  How do user values in Lua C API and lua_newuserdatauv function in particular work?
How do user values in Lua C API and lua_newuserdatauv function in particular work?

Time:02-04

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.

CodePudding user response:

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.

  • Related