How would I use ChildAdded (or something of the sort) for tables? I’ve asked other people but they told me to use loops, which clogs and isn’t that good.
(Example of a loop that I DON’T want to use due to it being a loop, laggy, etc.)
local Table = {};
while wait() do
if #Table then
print(Table[#1] .." is a new value of our table.");
end;
end;
Yeah, I’m basically in a situation where if I use a function in an event, the function doesn’t run because of the weird environment the event is in. So I have to use tables, but I can’t constantly check the tables with loops or else it’ll make the script performance bad.
I heard I could use __newindex, but I’ve never seen it being used before. Would you happen to know where I could find an example?
Donno how helpful would this be but before you add a value to the table, you could pass it through a value object then track it using the “.Changed” signal.
I’d need to create a function for that and in this case I literally can’t use a function. For some reason, when I create a function that only prints, it works, but when I create a function for a gui for example, it literally does not work.
GetChildren just returns the children of the table. I don’t want the contents of the table, I wanna know when they get added to the table, like ChildAdded.
Your solution is metatables, specifically the __newindex metamethod. __newindex fires whenever a blank index gets set to something, which is exactly what you want. There are plenty of threads on metatables, so I don’t want to explain them, however here is the developer hub article on them if you want: https://developer.roblox.com/en-us/articles/Metatables.
Here is a code example for what you want:
local Table = {}
setmetatable(Table, {
__newindex = function(_, index, value)
print(tostring(index) .. " has been added and set to " .. tostring(value))
end
})
--Examples:
table.insert(Table, "message") --> 1 has been added and set to message
table.insert(Table, 5) --> 2 has been added and set to 5
Table[3] = 0 --> 3 has been added and set to 0
Table[2] = 10 --nothing gets output, as the key 2 has already been set to something
Table.whatever = "hi :)" --> whatever has been added and set to hi :)
Table.whatever = "bye :(" --nothing gets output, as the key whatever has already been set to something
The solution is almost never metatables. You’re not wrong, but it is generally a better idea to just call a function when you change the table. Or make a custom function to do both.
That is actually what the linked post shows. I made the post titled “adding a changed event to a table.”
However, my method covers both ChildAdded and ChildRemoved in one single event.
What you’re looking for is metatable.__newindex. To entirely understand this, I recommend looking into Lua metatables a bit. In a sense, __newindex will fire when a new entry (with an index that hasn’t existed yet) is made.