Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Bad Argument #1 to "pairs" (table expected, got string) How can I fix?

Hello there I got this error: Bad Argument #1 to "pairs" (table expected, got string) so I actually tried to save a IntValue with Name and Value so and if I print the string it says [null] How can I fix that? Line 31 causes the issue after the error^

local DS = game:GetService("DataStoreService")

local PetDS = DS:GetDataStore("PetDataStore")

local PetsTable = {}

local AUTOSAVE_INTERVAL = 60

  

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

local PetsFolder = Instance.new("Folder")

PetsFolder.Name = "Pets"

PetsFolder.Parent = Player

local key = Player.UserId

print(key)

PetsTable = PetDS:GetAsync(key)

if PetsTable then

print(PetsTable)

game:GetService("HttpService"):JSONDecode(PetsTable)

for _,p in pairs (PetsTable) do

local In = Instance.new("IntValue")

In.Name = p["Name"]

In.Parent = PetsFolder

In.Value = p["Value"]

end

end

end)

  

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

PetsTable = {}

local key = Player.UserId

print(key)

for _,i in pairs (Player.Pets:GetChildren()) do

if i then

table.insert(PetsTable,i)

PetsTable[i] = {}

table.insert(PetsTable[i],"Name")

table.insert(PetsTable[i], "Value")

PetsTable[i]["Name"] = i.Name

PetsTable[i]["Value"] = i.Value

print(PetsTable[i]["Name"])

end

end

PetDS:SetAsync(key, game:GetService("HttpService"):JSONEncode(PetsTable))

end)

Thanks for answers!

3 comments

0

Post which line causes the issue. Also it is redundant to JSON encode a table to save to data stores; this is done by default.

0

Line 31 causes the issue let me edit it. Oh and it can't save it cause it is a Array so I need to Encode it per JSON.

0

I posted the solution

1 answer

✓ Accepted answer

Instead of just game:GetService("HttpService"):JSONDecode(PetsTable) do PetsTable = game:GetService("HttpService"):JSONDecode(PetsTable) JSONDecode doesn't change the value, it just returns the new one

3 comments

0

Sorry, I didn't realize what JSONDecode does at first. This should fix it

0

Now it dosen't saves just says: [null] when I try to print the json it says null

0

Also if I try it dosen't works and the error is gone

This discussion is preserved as it was. New answers, comments, and votes are closed.