Help with Luau Tables

Why does this chunk of code creates a new table inside the table every time?
When instead it should add on if table is created (I checked and it creates it correctly).
Screenshot (921)

Any help is highly appreciated!

Probably uh, because you repeatedly put things in the table? Just saying.

However, the table is created successfully, and then again same arguments are run through the block so I think my “if” statements are not doing what they should.

And yes this code is used repeatedly, to add onto the things in the table if the table wasn’t created then it gets created, and then it adds the values.

Within the inner if statements you are effectively doing:

t[#t] = val

… which just overwrites the last value in t (in your case it will place it at index 0 every time). You probably want:

t[#t + 1] = val
-- or, more idiomatically
table.insert(t, val)

You can clean the whole thing up, which would have made identifying and fixing this a lot easier, by doing something more like this:

if not ChatLogs[sender] then
    ChatLogs[sender] = {}
if not ChatLogs[sender][receiver] then
    ChatLogs[sender][receiver] = {}
table.insert(ChatLogs[sender][receiver], filteredMessage)

Thanks a lot for helping me out to fix this messy code.

I totally forgot about t[#t + 1] = val.

1 Like