Why is the table nil when I just defined it?

Hi! I am making a datastore system where you buy a tool and it gets added to a table. But the error says the table is nil. Here is my code:

local scope = "Tool"
local toolDataStore = game:GetService("DataStoreService"):GetDataStore("ToolSave")
local ownedTools = {}
local key = "-Tools"

game:GetService("Players").PlayerRemoving:Connect(function(player) -- Checking if player is leaving game
   local Success, Error = pcall(function()
   	return game:GetService("DataStoreService"):GetDataStore("ToolSave"):SetAsync(player.UserId..key, ownedTools)
   	-- Setting the data for inventory for the player
   end)
   if Error then
   	warn(Error) -- Showing there was error (Can also keep in log to fix)
   end
end)


remoteEvent.OnServerEvent:Connect(function(player, tool)
   print()
   if player.leaderstats.Coins.Value >= game.ReplicatedStorage.Tools[tool].Price.Value then
   	print(tool)
   	local Success, Error = pcall(function(ownedTools)
   		table.insert(ownedTools, 1, tool)
   		toolDataStore:SetAsync(player.UserId..key, ownedTools)
   		-- Cloning Tool --
   		local clonedTool = game.ReplicatedStorage.Tools[tool]:Clone()
   		player.Backpack:ClearAllChildren()
   		clonedTool.Parent = player.Backpack
   		-- Setting the data for inventory for the player
   		toolDataStore:SetAsync(player.UserId, ownedTools)
   		print("Done!")
   	end)
   	if Error then
   		warn(Error) -- Showing there was error (Can also keep in log to fix)
   	end
   else
   	print("Not Enough Money!")
   end
end)

This is the error: 17:08:46.409 - ServerScriptService.SnowConeBuyer:23: invalid argument #1 to ‘insert’ (table expected, got nil) Its on this line: table.insert(ownedTools, 1, tool)
Please help :confounded:

1 Like

You’re passing ownedTools as an argument to your pcall function, so the local reference in the scope of the function is given precedence. You can omit the argument for ownedTools from the pcall wrapped function and this should resolve this issue (since there is only one other reference to a variable named ownedTools)

1 Like

So if I delete the argument it should fix it?

Yup, that should fix the issue. As far as I can tell, this is likely what is causing your null reference issue.

1 Like