3.8 – Userdata
Userdata represents C values in Lua. Lua supports two types of userdata: full userdata and light userdata.
A full userdata represents a block of memory. It is an object (like a table): You must create it, it can have its own metatable, and you can detect when it is being collected. A full userdata is only equal to itself (under raw equality).
A light userdata represents a pointer. It is a value (like a number): You do not create it, it has no metatables, it is not collected (as it was never created). A light userdata is equal to “any” light userdata with the same C address.
In Lua code, there is no way to test whether a userdata is full or light; both have type userdata
. In C code, lua_type
returns LUA_TUSERDATA
for full userdata, and LUA_TLIGHTUSERDATA
for light userdata.
You can create a new full userdata with the following function:
- void *lua_newuserdata (lua_State *L, size_t size);
This function allocates a new block of memory with the given size, pushes on the stack a new userdata with the block address, and returns this address.
To push a light userdata into the stack you use lua_pushlightuserdata
(see 3.6).
lua_touserdata
(see 3.5) retrieves the value of a userdata. When applied on a full userdata, it returns the address of its block; when applied on a light userdata, it returns its pointer; when applied on a non-userdata value, it returns NULL
.
When Lua collects a full userdata, it calls the userdata’s gc
metamethod, if any, and then it frees the userdata’s corresponding memory.