How would I go about creating methods for objects?

This is something that you can do in Java so I was wondering if you can do it here.

Let’s say I have a IntValue and I want to create a method for it

function IntValue:Add(number)
  self.Value += number
end

TestingValue:Add(2)

That’s just a visual representation of what I’m trying to achieve, does anyone know any methods? I tried metatables but it isn’t quite what I need.

1 Like

Absolutely! While it isn’t supported by default in lua, there are some tricks

Link to full article: (Suggested Read) All about Object Oriented Programming - Resources / Community Tutorials - DevForum | Roblox

Here is an example:

local Car = {}
Car.__index = Car

function Car.new(carColor)
    local self = {}
    self.color = carColor
    return setmetatable(self, Car)
end

function Car:GetColor()
    return self.color
end

local carObj = Car.new("blue")
print(carObj:GetColor()) -- Returns blue

Thank you very much, it appears metatables were the way to go.

1 Like

By any chance, is there any way to implemented these custom methods to already existing Roblox objects, such as IntValues?

I’m pretty sure default roblox instances and such are read-only, however, you can make wrapper classes. Such as

local inst = Instance.new("IntValue")

local IntWrapper = {}

function IntWrapper.new(objToWrap)
	local self = {}
	
	return setmetatable(self,
		{__index = function(obj, key)
			return IntWrapper[key] or objToWrap[key]
		end})
end

function IntWrapper:GetValue()
	return self.Value
end

local int = IntWrapper.new(Instance.new("IntValue"))
print(int:GetValue(), int.Value) -- Both return 0, as that is the default value for IntValue's

Although the code may look overwhelming