OOP related question

I don’t know what to write in the topic. Sorry! If you guys can suggest what the topic is, please let me know so I can change it for other devs to refer to!

So I have this OOP code that creates a Countdown object where built-in functions such as Start and Stop can be called in the object. This object is created and put in a variable somewhere else.

local CountdownClass = {}
local CountdownObject = {}
CountdownObject.__index = CountdownObject

function CountdownObject:Start()
	while self.Countdown > 0 do
		if self.Stop == true then
			self.Stop = false
			break
		end
		
		self.Countdown -= 1
		task.wait(1)
	end
end

function CountdownObject:Stop()
	self.Stop = true
end

function CountdownClass.new(Start : number)
	local newCountdown = setmetatable({}, CountdownObject)
	newCountdown.Countdown = Start
	newCountdown.Stop = false
end

return CountdownClass

What I notice is that to get the countdown number itself, I may need to put a method that looks like this:

function CountdownObject:Get()
	return self.Countdown
end

Or get it like this but it’s repetitive:

local NewCountdown = CountdownClass.new(5)
NewCountdown.Countdown

But I just wondered if there is a way to refer to the object as the countdown number but still has these “hidden methods” that I can call upon?

Something like this:

local Countdown = CountdownClass.new(10)
print(Countdown) -- 10
Countdown:Start()
2 Likes

You can add a __tostring metamethod:

function CountdownObject:__tostring()
	return self.Countdown
end

local Countdown = CountdownClass.new(10)
print(Countdown) -- 10
Countdown:Start()
2 Likes

Is there a tonumber of metamethods?

No there isn’t but imo, don’t use these hacky metamethods, just use a getter function or directly index the value as its more efficient.

2 Likes

Oh alright. Guess I’ll directly index.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.