Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua weak reference

Tags:

lua

lua-table

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?

like image 233
MarkNS Avatar asked Mar 17 '15 21:03

MarkNS


People also ask

What are weak tables Lua?

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.

Does Lua have a 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.

What is a Metatable in Lua?

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.

What is a weak table Roblox?

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.


1 Answers

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.

like image 155
Etan Reisner Avatar answered Dec 03 '22 00:12

Etan Reisner