Hello, so im making something that detects when something in a table changes. It works fine, but I want to know how I can make it continue without runservice or while loops. Is it even possible? This is my script:
local MyTable = {
["Number"] = 10
}
while wait() do
local newtable = {
["Number"] = math.random(1, 5000)
}
for i,v in pairs(newtable) do
if not table.find(MyTable, v) then
print(newtable.Number)
end
end
MyTable = newtable
end
You could use recursion if youâre looking to not use loops or connections, though I assume thatâs not what you want.
The most practical way is just to have some code run when you make the change. For example, you could create a function called changeTable or a function called processTableChanged and run that function to change the table/when you change the table.
There also might be a metatable key for this. Iâll check.
Canât find one that would work specifically in the way you want.
Roblox instances etc. have events that fire when their properties change. The engine fires them after changing their properties.
Tables donât have that, so you have implement it yourself.
Seek out all the code that changes the table and make it run the function that should run when the table is changed.
You can avoid doing that by using a âproxy tableâ with __index and __newindex metamethods.
These will be run whenever something tries to read from a table and is about to get nil, and when something tries to overwrite a nil in a table.
local meta = {}
local realtable = {}
local MyTable = setmetatable({}, meta)
local function MyTableChanged(key, value, oldvalue)
print("MyTable changed to " .. value .. ", previous value was " .. oldvalue)
end
function meta.__index(self, key)
return realtable[key]
end
function meta.__newindex(self, key, value)
local oldvalue = realtable[key]
realtable[key] = value
MyTableChanged(key, value, oldvalue)
end
Not once have I ever had the need to detect changes in a table. Iâm sure that doing what youâre doing is unnecessary as there are other ways to store your data such as using values, which you can run GetPropertyChangedSignal() on and detect changes.