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

"attempt to index field "backpack" (a nil value)"?

im trying to make a script that saves data each 60 seconds but i get this error: "attempt to index field "backpack" (a nil value)" from my modulescript script:

local procX = require(workspace.GameHandler)
local GDS = game:GetService("DataStoreService")
while wait(60) do
	local plrs = game.Players:GetChildren()
	for i=1,#plrs do
		local plr = plrs[i]
	local plrid = plr.UserId
	print("plrname "..plr.Name)
	print("plrid "..plrid)
	local cashstat = plr.cash
		local cashstore = GDS:GetDataStore("cashes",plr.UserId)
		cashstore:SetAsync(plrid,cashstat.Value)
		local junk , stat = procX:statfromtool(plr,"dmg")
								local DSTORE = GDS:GetDataStore("rock",plr.UserId)
						DSTORE:SetAsync(plr.UserId.."_D",stat.Value)
	    print(stat.Value)
	    print(cashstat.Value)
	end
end

modulescript:

local module = {}
local rewards = {
	["Glass"] =  50,
	["GlassBarrierH1"] = 60,
	["GlassSentient"] = 100,
	["GlassBall"] = 80,
	["GlassLoot"] = 200,
	["GlassJumper"] = 150,
	["GlassBarrier"] = 200,
	["GlassBoss1"] = 320
}
module.processdestroy = function(naming,plr,hp)
local reward = rewards[naming]
if hp == 0 then do
plr.cash.Value = plr.cash.Value + reward
end
elseif hp < 0 then do
plr.cash.Value = plr.cash.Value + reward	
end
end
end
module.statfromtool = function(plr,stat)
	local tool = plr.Backpack:FindFirstChild("Rock") --problematic line
	if not tool then
		tool = plr.Character:FindFirstChild("Rock")
	end
	local stati = tool:FindFirstChild(stat)
	if stati then
		return stati.Value , stati
	end
end
return module

1 answer

✓ Accepted answer

When you use a colon to call a function on a table you are basically passing self as the first parameter into the function. self is a reference to the original value (in your case the table of the module) which you called the function on.

You have multiple ways you can fix this, you can:

  • Remove the colon invocation from procX:statfromtool() and replace it with a dot

  • In your module replace module.statfromtool = function(plr, stat) into module.statfromtool = function(self, plr, stat)

  • In your module replace module.statfromtool = function(plr, stat) into function module:statfromtool(plr, stat)

1 comment

0

thanks

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