Help with OOP, undefined method?

My desired goal is to get it to where every time I call the :eat() method, a certain amount of “juiciness” is taken away from the given fruit.
My current problem is that when I call pineappl3:eat() (code provided below), I get an error (attempt to call a nil value)

local pineapple = {
	__type = "Fruit",
	__index = {
		-- Defaults go here
		juiciness = 10,
		jpb = 3, -- "juiciness per bite" => how much juiciness is lost per bite
	},
}

function pineapple.new(value)
	local self = setmetatable({}, pineapple)
	self.juiciness = value or self.juiciness
	return self
end

function pineapple:eat()
	local self = setmetatable({}, pineapple)
	if self.juiciness >= self.jpb then
		self.juiciness = self.juiciness - self.jpb
		print(self.juiciness)
	end
end

local pineappl3 = pineapple.new()
pineappl3:eat()

The solution I tried was by changing pineappl3:eat() to pineapple:eat(), which worked at first, but didn’t work as intended when I called it twice and the juiciness was 7 and not 4.

Hey there! I’m not that experienced of a coder but the values properties of a new instance are supposed to be in the normal table, not the meta table. The meta table’s __index is supposed to lead to itself. Sorry if I made no sense.

The fixed code:

local pineapple = {}
pineapple.__index = pineapple

function pineapple.new(value)
	local self = {
		__type = "fruit",
		juiciness = 10,
		jpb = 3
	}
	setmetatable(self, pineapple)
	return self
end

function pineapple:eat()
	if self.juiciness >= self.jpb then
		self.juiciness = self.juiciness - self.jpb
		print(self.juiciness)
	end
end

local pineappl3 = pineapple.new()
pineappl3:eat()
1 Like

This is correct. This should be the proper solution.

Ohh, that makes so much sense. Sorry I’m new to using OOP but thanks!