How can I make this repeat without while loops or runservice?

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

Any help is appreciated

It can go in #help-and-feedback:scripting-support too.

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.

1 Like

I will try this. Thank yoiu for telling me thsi

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

(untested)

2 Likes

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.

1 Like

worked . Only issue was. It would say old value was nil. And it doesn’t work with table.insert. Only with table[1] = thing here