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


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

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

function Car:GetColor()
    return self.color

local carObj ="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 ="IntValue")

local IntWrapper = {}

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

function IntWrapper:GetValue()
	return self.Value

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

Although the code may look overwhelming