Hello, I am trying to code a data store that saves multiple data in a table, but apparently, it pops up with the error;
“attempt to index number with number”.
local Service = game:GetService("DataStoreService")
local Key = Service:GetDataStore("LyfeDataStore_1")
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder")
leaderstats.Parent = plr
leaderstats.Name = "leaderstats"
local val = Instance.new("IntValue")
val.Parent = plr
val.Name = "Cash"
local data
local success, result = pcall(function()
data = Key:GetAsync(plr.UserId)
end)
if success then
-- SUCCESS
if data then
val.Value = data[1]
plr:FindFirstChild("leaderstats"):FindFirstChild("Age").Value = data[2]
end
else
warn("ERROR")
error(result)
end
end)
game.Players.PlayerRemoving:Connect(function(plr)
local data = {plr:FindFirstChild("leaderstats"):FindFirstChild("Cash"), plr:FindFirstChild("leaderstats"):FindFirstChild("Age")}
local success, result = pcall(function()
Key:SetAsync(plr.UserId, data)
end)
if not success then
warn("ERROR")
warn(result)
end
end)
You’re only retrieving the Instance of the data variable, not the Instance.Value
If you want the values to save, consider saving their Value properties instead of the Instance of it
Also, don’t call FindFirstChild whenever you’re trying to find a leaderstat value as soon as a player joins (You should always create it yourself in that same exact script, or call WaitForChild() instead)
local Service = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local Key = Service:GetDataStore("LyfeDataStore_1")
Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder")
leaderstats.Parent = plr
leaderstats.Name = "leaderstats"
local Age = Instance.new("IntValue")
Age.Name = "Age"
Age.Parent = plr
local val = Instance.new("IntValue")
val.Name = "Cash"
val.Parent = plr
local data
local success, result = pcall(function()
data = Key:GetAsync(plr.UserId)
end)
if success then
-- SUCCESS
if data then
val.Value = data[1]
Age.Value = data[2]
end
else
warn("ERROR")
error(result)
end
end)
Players.PlayerRemoving:Connect(function(plr)
local leaderstats = plr:WaitForChild("leaderstats")
local Cash = leaderstats:WaitForChild("Cash")
local Age = leaderstats:WaitForChild("Age")
local data = {
Cash.Value,
Age.Value
}
local success, result = pcall(function()
Key:SetAsync(plr.UserId, data)
end)
if not success then
warn("ERROR")
warn(result)
end
end)
Sometimes it’s better to yield for trying to find these values rather than just “assuming” that they’re already in your Player, as worst case scenario it returns back an error
Both SetAsync and GetAsync are yielding functions, and won’t continue until a result is made inside those pcall functions
If you’re trying to call FindFirstChild while you’re still creating the Age variable somewhere else without any sanity checks, it might result back as an error hence why you’re assuming that the leaderstats, and the Age names are already there