Singleton in C API

19 views
Skip to first unread message

Stefano Cossu

unread,
11:00 AM (6 hours ago) 11:00 AM
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)?

Thanks for any suggestions,
s
OpenPGP_0x1716A1B35E826596.asc
OpenPGP_signature.asc

Sainan

unread,
2:09 PM (3 hours ago) 2:09 PM
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.

-- Sainan
Reply all
Reply to author
Forward
0 new messages