What am I doing wrong? Basic OOP

Hello so I am learning how to use metatables because before I never had any use of it.
So I will get straight to the point.

Module Script

local Pizza = { }
Pizza.__index = Pizza

function Pizza.new(flavor, slice_count)
    local this = { }
    this.Flavor = flavor
    this.Slices = slice_count
    setmetatable(this, Pizza)
    return this
end

function Pizza:Eat()
	if self.Slices <= 0 then return end
    self.Slices -= self.Slices
end

return Pizza

Script

local modu = require(workspace.ModuleScript)


local p2 = modu.new("nicenice", 3)
p2:Eat()
print(p2.Slices)

When I run this I get Host:6: attempt to call a nil value
So on the 6th line it errors because its a nil value and I dont know why because I think I have declared the value.

change that to

  setmetatable(this, {__index = Pizza})

and it’ll work,

this will always just set self.Slices to 0, did you mean to maybe subtract a certain amount instead?

1 Like

Thanks it worked perfectly :slight_smile:

Yeah I meant to subtract by 1, I didnt notice that at all oof.

1 Like