I can’t understand tables and how to insert data into them. I have searched all over YouTube and the DevForum to find something similar that can guide me. I have learned the basics of tables (how to create them and a couple of essential functions), but I don’t know how to insert a value in them (for example if we have “Coins”, a NumberValue, how do I insert it?). Then how can I save them and load them back to the player (I have heard that BindToClose might be suitable for saving when the player leaves)? This might seem a bit excessive, but I am getting kinda desperate since I can’t find anything that works well. Please help!
You can use the method table.insert(t, value) to insert a specific value into a table e.g:
local newTable = {}
table.insert(newTable, 'a')
table.insert(newTable, 'b')
table.insert(newTable, 'c')
print(table.unpack(newTable)) -- a, b, c
You can also use the third argument to insert the value to a specific index e.g: table.insert(newTable, 'd', 1) would make ‘d’ the first in the array (it would print d,a,b,c)
Then you would use DataStoreService to save the player’s data there are many tutorials on how to do so including the DevHub: Introduction to Saving Data
Wow, thank you so much! I never thought it was this easy. Though I had some problems with PlayerRemoved in the past when saving (sometimes it wouldn’t save because the server would close before the values would save, since that was the last player on it). I have seen people using BindToClose and it would save the player’s data before the server shuts down. How can I apply it here? Or is it just better to stay with the PlayerRemoved function?
BindToClose() basically fixes your problem as this event fires a few seconds before the server shuts down:
it wouldn’t save because the server would close before the values would save
You would use it in the sense that you would go over all of the players in the server using a for loop and save their data before the server dies out e.g:
game:BindToClose(function()
local players = Players:GetPlayers()
for _, player in pairs(players) do
local userId = player.UserId
local data = playerData[userId]
if data then
local success, result = pcall(function()
dataStore:SetAsync(userId, data)
end)
if not success then warn('Not saved')
end
end
end)