Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

OOP Help: Attempt to index nil value?

Asked by 5 years ago

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.

0
Could it be that you're referring the Backpack in an incorrect position? Lugical 425 — 5y
0
What is self? Because the script not find BackPack on self. Maybe use :WaitForChild() "self:WaitForChild('Backpack')[Item]" NiniBlackJackQc 1562 — 5y
0
No. User#19524 175 — 5y
0
You clearly don't know OOP, don't even ask... User#19524 175 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago

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

0
Ye User#19524 175 — 5y
Ad

Answer this question