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

How can I fix this table saving? (Attempt to get the lenght of upvalue "Pets" (A nil value)

Asked by 5 years ago

Hello Community,

I have a problem the output is saying at my table save script: "Attempt to index upvalue of "Pets" (A nil value) how could I fix this?

My script:

local PetSave = game:GetService("DataStoreService"):GetDataStore("Pets")

local Pets = {}

local Number = 1

game.Players.PlayerAdded:Connect(function(Player)

local PetsFolder = Instance.new("Folder")

PetsFolder.Name = "Pets"

PetsFolder.Parent = Player

local Key = Player.UserId

Pets = PetSave:GetAsync(Key)

end)

game.Players.PlayerRemoving:Connect(function(Player)

for index = 1, #Pets do

table.remove(index)

for _,p in pairs (Player.Backpack:GetChildren()) do

table.insert(Pets, Number, p.Name, p.Value)

end

local Key = Player.UserId

PetSave:SetAsync(Pets, Key)

print("savedi")

end

end)

0
It's probably because there's nothing in the "Pets" table. Mr_Unlucky 1085 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago

https://developer.roblox.com/api-reference/function/GlobalDataStore/SetAsync

SetAsync(key, value)

In your script, you accidentally made the key the Pets variable and the value to Key It should be:

local Key = Player.UserId
PetSave:SetAsync(Key, Pets)

But your script is wrong either way, it won't save what you want it to save.

Learning DataStores

I reccommend you read up and use references from a tutorial on how to use DataStores: https://developer.roblox.com/articles/Data-store https://developer.roblox.com/articles/Saving-Player-Data

What you did incorrectly is made a global table that gets replaced when a new player joins.

local table = {}
--table is an empty bracket

Players.PlayerAdded:Connect(function(player)
    table = DataStore:GetAsync(key)
    --table is now the player's data
end)

Every time a player joins, table gets replaced by the new player's data. This will make everyone's data save to this new player's data.

Correct way:

local table = {}
--table is an empty bracket

Players.PlayerAdded:Connect(function(player)
    table[player] = DataStore:GetAsync(key)
    --you created a dictionary that can be access by table
end)

Player.PlayerRemoving:Connect(function(player)
    local accessData = table[player]
    --table has this player's data in a dictionary,
    --we can access this
end)

Yes, you can do it like this, but you need to look at how ROBLOX recommends you do it. DataStores can error causing players not have their data saved. pcall is used to keep the code running, even when an error happens. Won't get into detail, just know you are going to use it.

table.insert(table,position, value)

What you tried to do is insert multiple values into a table. You can only insert one value at a time. https://developer.roblox.com/api-reference/lua-docs/table

Ad

Answer this question