is there a way to be able to check if a table has been updated, and if it does can it run a line of code?
You’ll have to use run service or while loop and check if the table has changed/updated, and if you find a difference then you can execute a code!
You cannot detect when variables are changed, regardless if it’s a table or not.
Whenever you want to add something to a table in the script, you can run the function directly after.
Example:
local plrs = {}
local function tableUpdated(t, value)
print(value .. " was just added to a table!")
end
game.Players.PlayerAdded:Connect(function(plr)
plrs[plr.Name] = plr
tableUpdated(plrs, plrs[plr.Name])
end)
While this is useless as you can do game.Players:GetPlayers() this is just an example.
Also, make sure to read the posting guidelines for #help-and-feedback:scripting-support (here)
main
is the table you’ll index when getting or setting values. The values will automatically be set to or fetched from data
by the metamethods. Here’s some information about metatables and metamethods.
local main = {}
local data = {}
local mt = {}
mt.__index = data
function mt:__newindex(key, val)
data[key] = val
print("update: "..tostring(key).." = "..tostring(val))
end
setmetatable(main, mt)
@RoBuPoJu 's solution works for MetaTables, but the closest thing you will get to is a :WaitForChild()
for tables.
local RunService = game:GetService("RunService")
local function WaitForChildInsideOfTable(Table: table, ThingToWaitFor: string)
while RunService.Heartbeat:Wait() do
if Table:find(ThingToWaitFor) then
break
return
end
end
end
Use Case:
local Table = {"Hello!", "Bye!"}
local function WAITTTTthenadd()
wait(10)
Table:insert("Cya Later :)")
end
WAITTTTthenadd()
WaitForChildInsideOfTable(Table, "Cya Later :)")
print("Cya later :)")
You can also make functions for waiting for spesific keys or values using metatables and coroutine functions. The function :WaitForValue below will wait for a spesific value to be added to an ‘object’ table created by Class.new(). I don’t know in what situation waiting for a spesific value to be added to a table would be useful, though.
local Class = {}
function Class.new()
local obj = {
ValWaitCoroutines = {},
Data = {}
}
return setmetatable(obj, Class)
end
function Class:WaitForValue(val)
for _, v in pairs(self.Data) do
if v == val then
return
end
end
local valWaitCoroutines = self.ValWaitCoroutines
local t = valWaitCoroutines[val]
local routine = coroutine.running()
if not t then
valWaitCoroutines[val] = {routine}
else
table.insert(t, routine)
end
coroutine.yield()
end
function Class:__index(key)
return self.Data[key] or Class[key]
end
function Class:__newindex(key, val)
self.Data[key] = val
local valWaitCoroutines = self.ValWaitCoroutines
local coroutinesToResume = valWaitCoroutines[val]
if coroutinesToResume then
valWaitCoroutines[val] = nil
for _, routine in ipairs(coroutinesToResume) do
coroutine.resume(routine)
end
end
end
return Class
I usually do this by creating a proxy for the table.