Question

Is there a way for C to reference an object in Lua 5.2 in the same way that you would use the reference system except that these references are weak and may be garbage collected at any time? In other words, is there a registry of all current Lua objects that does not influence the objects' reference count?

Was it helpful?

Solution

You can do this by introducing one level of indirection - instead of storing the values directly in registry and forcing it to be weak, do this:

  1. Create a table
  2. Make it weak by setting a metatable {__mode = "v"}
  3. Store this table in the registry using some known but unique key
  4. Keep all objects you want to track in this table
  5. Use this table stored in registry instead of the registry itself to look up all your objects

Note that there is no "track of all Lua objects" (like ObjectSpace in Ruby), unless you use some heavy persistence like Pluto. You can only access objects you store/track yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top