I’ve wrote some extremely nice code for a stackoverflow question:
(Already reached enough reputation for the ROBLOX Commitment 2d ago, but eh)
Someone wanted a way of having “dynamic variables”, basicly auto-updating fields.
Imagine you have a table with the fields bananas and price.
bananas is just a number, let’s say we set it to 10 by default.
price has to be bananas * 3.
With my code, you can make that table using this code:
local test = DependenceTable()
test:Register("bananas",10)
test:Register("price",function(self) return self.bananas*3 end)
The price constructor gets called once during Register, the value is cached.
Now when you set test.banana to something else, the number 30 for example;
It’ll see “Ah, price depends on bananas, let’s also update it” and it updates.
Printing test.price would result in 90.
I actually made it work with subtables, so you can do haxy stuff like:
test:Register("data",{something=123})
test:Register("idk",function(self) return self.data.something + 5 end)
print(test.idk) --> 127
test.data.something = 100
print(test.idk) --> 105
test.data = {something=0}
print(test.idk) --> 5
The constructor only gets called when one of the property’s dependencies changes.
(In this case idk only changes when data changes, in no other case)
It’s like like indexing test will trigger a recalculation.
You can chainlink the dependencies:
A uses B, B uses C.
Editing C would update B, which would update A.
Editing B would just update A.
(I’m way too proud I made this, hence I’m showing it off now)