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

OOP Help: Attempt to index nil value?

Trying to get started with OOP and decided to make an Inventory object

Here is my ModuleScript called "Inventory"

local Inventory = {}
Inventory.__index = Inventory

function Inventory.New(Player)
	return setmetatable({
		Player = Player;
		Backpack = {
			["Coins"] = {Name = "Coins", Quantity = 0, Description = "Lovely money!"}
		};
	}, Inventory)
end

function Inventory:AddItem(Item, Quantity)
	if self.Backpack[Item] and Quantity >= 0 then
		-- Check if the Item is an actual Item available in the backpack and
		-- were adding a positive number
		self.Backpack[Item].Quantity = self.Backpack[Item].Quantity + Quantity
		return self.Backpack[Item].Quantity
	end
	return false
end

function Inventory:GetQuantity(Item)
	if self.Backpack[Item] then
		-- Check if the Item is an actual Item available in the backpack
		return self.Backpack[Item].Quantity
	end
	return false
end

return Inventory

My issue is that when I run Inventory:GetQuantity("Coins") I get the error:

ServerScriptService.Inventory:24: attempt to index field 'Backpack' (a nil value)

How come that doesn't work but when I call Inventory:AddItem("Coins") it works? The issue might not be because of OOP and I'm just not seeing something.

4 comments

0

Could it be that you're referring the Backpack in an incorrect position?

0

What is self? Because the script not find BackPack on self. Maybe use :WaitForChild() "self:WaitForChild('Backpack')[Item]"

0

No.

0

You clearly don't know OOP, don't even ask...

1 answer

Found my mistake.

In the server Script (Not the module) I was doing

Inventory:GetQuantity("Coins") 

not the correct way:

 NewInventory:GetQuantity("Coins") 

Feel kinda stupid, but I'm glad I "fixed" it

1 comment

0

Ye

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