lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Aug 21, 2015 at 12:27:39AM +0100, Dibyendu Majumdar wrote:
> Hi,
> 
> Apologies for this very basic question. What is the purpose (i.e. use
> case) of the lua_setuservalue() api?
> 

It allows you to associate a Lua object to the userdata without having to
use lua_ref. lua_setuservalue is O(1) while lua_ref is O(log N). More
importantly, uservalues can reference the userdata. The reference cycle
would be hidden from the GC using lua_ref, creating a memory leak.

lua_getuservalue is probably a little more efficient in real terms--if not
algorithmically--because it doesn't have to index a table.

I've never once used uservalues. I keep forgetting about them. I _should_ be
using them, though. In my cqueues module--an event library--I use ephemeron
tables to store references to coroutines to prevent memory leaks if the
coroutines hold references to the cqueue controller object. But ephemeron
tables have horrendous algorithmic complexity. I should open a ticket on
that right now!