Today I found an error when I’m trying to creating a DataStore system that stores player data in Dictionary form
So first, I made a table that shows all data required and where should the data be send to
local DataRequired = {
["Wins"] = {
leaderstats:WaitForChild("Wins")
}
}
And here is where the script will loop through the dictionary
-- DataType refers to the current item it is looping through
-- Data refers to the result from :GetAsync()
for DataType, Data in pairs(data) do
for _, DataValue in pairs(DataRequired[DataType]) do
if DataType[DataValue] then
-- Set value
DataValue.Value = DataType[DataValue]
end
end
end
But it gave me an error like this :
ServerScriptService.DataScripts.DataScript:43: invalid argument #1 to 'pairs' (table expected, got nil)
Can someone explain why and tell me how to fix this?
Hello! You’re trying to loop through a nil value while it was expecting an table. First you should check if data is nil, making sure it exists.
And you’re trying to loop through DataRequired[DataType], but in DataType[DataValue] you’re treating DataType as a table, but it’s a key from data.
I think you should access the value from data table directly, using the key DataType. I’ll show you a way, check it.
-- First make sure data exists, then loop data.
if data then
for DataType, DataValue in pairs(data) do
-- Get the dataTarget directly from DataRequired
local dataTargets = DataRequired[DataType]
if dataTargets then
for _, target in pairs(dataTargets) do
-- Set the value if it exists
if DataValue then
target.Value = DataValue
end
end
end
end
else
warn("No data found,")
data = {} -- Initialize with default table
end