I'm aware of the weak tables functionality in Lua, however I would like to have a weak reference with a single variable.
I've seen this proposal which suggests an API as follows:
-- creation
ref = weakref(obj)
-- dereference
obj = ref()
which would seem ideal. However this doesn't appear to be in the documentation elsewhere; only weak tables.
Is there something analogous to Python's weak reference to object functionality?
Weak tables are the mechanism that you use to tell Lua that a reference should not prevent the reclamation of an object. A weak reference is a reference to an object that is not considered by the garbage collector.
Lua uses a garbage collector that runs from time to time to collect dead objects when they are no longer accessible from the Lua program. All objects including tables, userdata, functions, thread, string and so on are subject to automatic memory management.
Metatables are the Lua method for creating objects and altering the behavior of operators such as +, -, [], etc. Every value in Lua can have a metatable. This metatable is an ordinary Lua table that defines the behavior of the original value under certain special operations.
Lua implements weak references as weak tables: A weak table is a table where all references are weak. That means that, if an object is only held inside weak tables, Lua will collect the object eventually. This is where weak tables come in. A table's keys and/or values can be weak.
Something like this can do what you want I believe:
local obj = {value = "obj.value"}
local ref = setmetatable({real = obj}, {__mode = "v", __call = function(self) return self.real end})
print(obj.value)
print(ref.real.value)
print(ref().value)
obj = nil
collectgarbage()
collectgarbage()
print(obj)
print(ref.real)
print(ref())
The __call
part is optional but gives you the ref()
call syntax. Without it you have to use the direct access version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With