Invalid argument #2 to 'insert' (number expected, got string)

So, I’m creating a script which is supposed to save the ammount of boomboxes in your storage, and my way of applying it is by using a module, this is what it looks like at the start:

return {
	["Cheap Boombox"] = true,
	["Rarer Boombox"] = false,
}

pretty simple, but I get this error from my saving script:
invalid argument #2 to 'insert' (number expected, got string)
I’m not sure what’s going wrong?

local V1PER = require(game.ReplicatedStorage.V1PER)

local OwnedBoomboxes = game:GetService("DataStoreService"):GetDataStore("OwnedBoomboxes")

game.Players.PlayerAdded:Connect(function(Player)
	local Data = V1PER.DataStoreResource.Builder.BuildNewLeaderstats({
		{
			Name = "Music",
			TypeValue = "Int",
			Default = 0
		}	
	}, Player)
	
	V1PER.DataStoreResource.DataStore.LoadData(Player, Data)
	
	local retrievedData
	
	local found, errorOccured = pcall(function()
		retrievedData = OwnedBoomboxes:GetAsync(Player.UserId.. "$")
	end)
	
	if found then
		if retrievedData then
			if type(retrievedData) == "table" then
				local BoomboxesOwned = script:WaitForChild("BoomboxesOwned"):Clone()
				table.clear(require(BoomboxesOwned))
				for boombox, owned in pairs(require(retrievedData)) do
					table.insert(require(BoomboxesOwned), boombox, owned)
				end
			else
				error("Cannot be an instance type that is not a table!")
			end
		else
			local BoomboxesOwned = script:WaitForChild("BoomboxesOwned"):Clone()
			BoomboxesOwned.Parent = Player
		end
	else
		error(errorOccured)
	end
end)

game.Players.PlayerRemoving:Connect(function(Player)
	V1PER.DataStoreResource.DataStore.SaveData(Player)
	local returnTable = {}
	for Boombox, Owned in pairs(require(Player:WaitForChild("BoomboxesOwned"))) do
		table.insert(returnTable, Boombox, Owned)
	end
	OwnedBoomboxes:SetAsync(Player.UserId.. "$", returnTable)
end)

The second argument of table.insert is the index (Number) where you want the added data to go. Right now you’re looping through the booxbox table → and trying to insert the “owned” value into a position of a string (since boombox is a string and not a number).

I don’t think you should be using table.insert for a dictionary. You usually use most table methods on an array.

You should instead do something like:

local MyBoomBoxes = {};
for boombox, owned in pairs(require(retrievedData)) do
	MyBoomBoxes[boombox] = owned;
end

-- then do whatever you want with the MyBoomBox dictionary.

Note there may be typos as I’m writing in this on mobile!

2 Likes