You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to lua-l
Hello there,
I want to implement a singleton in the Lua C API. A `new()` function
should check if an object with a unique ID (simply obtained by
concatenating a static prefix and the arguments passed to the function)
exists in the registry: if it exists, a reference to the existing one
should be returned, otherwise a new object is created and returned.
The object should be unique per process and should span across threads.
I have looked around possible options for this, including using light
userdata references, but I can't figure out how to correctly garbage
collect multiple instances of the singleton. If the first instance
(which contains the full userdata object) is garbage-collected first,
the other instances will be pointing to garbage.
Alternatively, since this singleton restriction is only on the C pointer
(the C library I am using mandates that a handle be unique within a
process), I could create multiple full userdata objects containing the
same C pointer. Here again, though, I don't know how I would finalize
the C structure when all its references are garbage-collected.
I also thought about creating the object in the global table and
returning a full userdata reference if the object has been already
created. Would Lua take care of garbage collection of the main object (I
guess when the process ends...?) and its references (when they get out
of scope)?
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to lu...@googlegroups.com
I think the 'require' mechanism is kind of what you want. Each library is only required once, with subsequent calls to require simply reusing the library instance. 'package.preload' may help you easily register a named 'singleton constructor' function.