I have a table inside a module script, and I have a function to add a value to it. When I add a value, it doesn’t update in time, so when I print it in the next line, it still prints as an empty table. Here’s what I mean:
This is a print statement in the line immediately after the function call in the module script to add a value to it.
This is inside the function call, inside the module script.
function directory:add(data : string)
if typeof(self.current) ~= "table" then error(string.format("Can't insert into type %s", typeof(self.current))) end
table.insert(self.current, data)
print(self.current, tick())
end
But if I add a task.wait for about a second, it prints correctly.
what’s happening here is that game.Players.PlayerAdded:Connect only connects a function to an event. the function only runs when that event fires, so the print statement ends up running first because it runs immediately after you connect the function to PlayerAdded but before a player actually joins.
the reason why it works when you use a task.wait is that it pauses the current thread and schedules it to resume later, so by the time it is set to resume a player has connected.
It seems like the actual function is working just fine. if you were to put the print statement inside of the function connected to PlayerAdded, you would end up getting the correct results.
i guess you can use game.Players.PlayerAdded:Wait() before the print statement. it works like task.wait but instead of waiting for a specific amount of time, it waits for a player to join.
That wouldn’t really work. I would have to modify something inside of the module script because if I ever release this, I don’t want the user putting game.Players.PlayerAdded:Wait() in every one of the scripts that the use for this.
there no way for you to access data that doesn’t exist. if you add data when a player joins they only way for you to have that data available is to wait for it to be added.