What is the difference between userdata and light userdata?

lua_newuserdata allocates a block of memory of the given size. The result is called a userdatum, and differs from a block allocated with malloc in two important ways: first, it will be collected by the garbage collector, and second its behaviour can specified by a metatable, just like with Lua tables. There are two metamethods which can only be used with userdata; __len implements the size operator (#) and __gc provides a function which will be called when the userdatum is garbage collected. A good example of this in the standard Lua library are file types, where __gc will close the file handle. The metatable also acts as the unique type of a userdatum.

Light userdata, on the other hand, are simple wrappers around a C pointer. They don't have metatables, and aren't garbage-collected. Their purpose is to generate unique 'handles' which can be cheaply compared for equality.

The implementation of a simple array object is discussed in PiL, starting with a simple set of functions and ending up with an object which can be indexed like a regular Lua table.

8 Lua 5.2

The beta version of Lua 5.2 is available from here, currently as 5.2.0-beta. The global variable _VERSION will be the string "Lua 5.2", if you need to check for compatibility. See this wiki page for another catalog, and an in-depth analysis here.



Back