function UpdateStorages() for index, value in pairs(storages) do value.Items.ChildAdded:connect(function() print("did it") UpdateGui() end) end end
I know how events work, but I have a constantly changing table and I want an event on each. This obviously doesn't work. Any ideas on how to do it?
What I would do in this event is create a connections table and a regular table. The regular table would be equivalent to your 'storages' table.
I made an example to test how this can work:
connections = {} storages = {} setmetatable(storages, {__newindex = function(self,ind,val) connections[#connections + 1] = val.ChildAdded:connect(function(a) print("Did it!") end) end}) function insert(tab,thing) tab[#tab + 1] = thing end local f = Instance.new("Folder",workspace) insert(storages,f) wait(1) Instance.new("Script",f)
In the test scenario above, each time something new is added to 'storages', it gives it an event which is added to connections. I do believe I am over-complicating what you may be asking, but this is a good concept on how to add new things to a table with an event without having to constantly loop and reset the connections.
If I didn't get what you were asking for, PLEASE comment. I truly am here to help.
If the storage has a fluctuating size, you should delete the connections when they are no longer needed. You can do this without metatables:
storages = {} --I'm treating storages as a dictionary where the storage object is the key and the event it is connected to is the value function AddToStorages(obj) if storages[obj] then return end --already have this object recorded storages[obj] = obj.ChildAdded:connect(UpdateGui) end function RemoveFromStorages(obj) local con = storages[obj] if not con then return end --obj not in storage con:disconnect() --disconnect the event to prevent it from firing storages[obj] = nil --remove obj from storage end --If you need to iterate over the contents of storage, do: for obj, con in pairs(storages) do --obj is the storage object, 'con' is the connection to the ChildAdded event end
Though you could use metatables, you'd have to come up with some convention, like "storages[obj] = true
means add to storage and storages[obj] = false
means remove it", or perhaps use the __call metamethod and then you could do "storages(obj, true)
or storages(obj, false)
" to add/remove it the obj from the storages list. (EDIT: Note that you'd also have to use a table other than 'storages' to store the actual content, or else the metamethods would not get invoked. See http://www.lua.org/pil/13.4.4.html for details.) In either case, it isn't obvious what's going on by just looking at the calling code -- "AddToStorages(obj)" is clearer than "storages[obj] = true"; thus, I recommend just using the functions.