Garry's Mod Wiki

Concepts - Userdata

Userdata

Userdata is a type primarily used in the Lua C API that points to
C data - such as objects - and comes in two flavors, full & light.


Full Userdata

When people mention userdata they likely refer to full userdata.

Most of the time you will encounter full userdata objects,
such as panels & entities that function similar to tables.

Create empty userdata with newproxy.


Details

Full userdata can have metatables, however it won't be indexed,
and will not work with functions in the table library.

Arbitrary values can be assigned to types like entities because
of the entity userdatum's metatable, which uses the __newindex
metamethod to set values in the entity's internal Lua table.

Correspondingly, the __index metamethod checks the
entity's internal Lua table for the key, and returns its value.

It is through these functions that types like
entities can be indexed as if they are tables.

Full userdata is garbage collected, and Lua lets full userdata
know it's about to be collected by calling the userdata's __gc
metamethod, passing the userdatum itself as an argument.

This allows for any resources used by the userdata to be freed
on the C side, such as deleting an object or releasing a file handle.


Light Userdata

Light userdata represents a pointer as a value in Lua.


Details

Unlike full userdata, light userdata is not garbage collected,
has no individual metatable, and is only equal to other light
userdata when the pointers they hold are equal.

This is not inherently used in Garry's Mod.

See the Programming in Lua documentation for more information.