Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Help with tables?

Asked by 9 years ago

Ok,so I was making a chat log and I wanted to make a ChatAdded event but then I had a hard time thinking how to check if something has been added to the table so then I came with getting the number of chats in a moment then subtracting it the number of chats once the player has chatted but it didn't work.

TLDR: Is there another way I can check if a new value has been added in the table?

ChatLog = {}
--------------------Vairbles----------------------------
NewChatAdded = script.NewChatAdded
------------------Functions-----------------------------
function ChatLogInsert(String)
        table.insert(ChatLog,#ChatLog,String)
end
----------------------Events----------------------------
NewChatAdded.Event:connect(function()
    while wait() do
        ChatLogNow = #ChatLog--Kinda Like Tick()
        ChatLogLater = #ChatLog
         NewChats = math.floor(ChatLogNow-ChatLogLater)
          if NewChats > 0 then
                print("New chats!")
            return true
                else return false
        end
    end
end)
---------------------------------------------------------
game.Players.PlayerAdded:connect(function(Player)
    Player.Chatted:connect(function(Chat)
        ChatLogInsert(Chat)
            NewChatAdded:Fire()

    end)
end)

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

There is no super-elegant way to track changes to a table.

Using metatables, you can fire an event whenever a value is set in a table (e.g., tab[#tab] = 5). However, this will not capture modifications made with table.insert (because of table.insert's capacity to completely shift a table's elements) or table.remove (for the same).

Those functions could be modified to also track those changes, but it becomes more complicated.


If you don't need to grab the change the moment it happens, and just a heart-beat check works (check thirty times a second, for example), the solution is to make a copy of the table and remember it in the next thirtieth of a second, comparing all keys (including looking for any deletions/insertions).


However, what you have is a much better solution for this particular problem. You are not looking for arbitrary changes, you are just looking for insertions. Utilizing a function the function like you are is nearly a very-well-made solution.

The only change that might make it more elegant would be to pass the message as an argument, and allow the NewChatAdded event to insert the chat as well, which may be more elegant, rather than using the background table to look at what was added.

0
If I do pass the message as a argument,then how will I change it like Ex : function (this)<---- How would I change this? kevinnight45 550 — 9y
Ad

Answer this question