Can you make a custom function to roblox instance?

As for the recent time, i’ve dwelled into metatables and stuff related to it, has finally found an use and application for it. Turns out metatables are surprisingly very useful and practical for coding flexibility and re-usability, and im looking forward to learn more about it and definitely not going to misuse it or using it unnecessarily.

Anyway, setting that aside. I have curious question if there’s a way to make custom function to roblox existing instance like humanoid. Basically extending its use to your own liking and need (Script below for example of what i mean)

-- Let's say i write this in module script and do stuff to make it work
function Humanoid:CheckAirborne()
      return Humanoid.FloorMaterial == (Enum.Material.Air or nil)
end

-- So you can do this in other script
local isAirborne = Humanoid:CheckAirborne()

I don’t know how to end this post poetically. But basically that question.

you cannot add methods/functions to Roblox instances
though you can make a custom wrapper which can look smt like this

local HumanoidWrapper = {}
local HumanoidMt = {}
HumanoidMt.__index = HumanoidMt


function HumanoidWrapper.new(humanoid :Humanoid)
	local self = setmetatable({}, HumanoidMt)
	self.Humanoid = humanoid
	
	return self
end

function HumanoidMt:CheckAirborne()
	return self.Humanoid.FloorMaterial == (Enum.Material.Air or nil)
end

return HumanoidWrapper

1 Like

That’s unfortunate that you can’t give Roblox Instances custom function for your own work.

I’ve tried to work around with this limitation by making custom mt like the one you made, but replicating the humanoid whole property, function, and event to a table and use __newindex to detect property change (Since now the humanoid is table, if i try to change the property, it would only change the table value instead). But turns out you can’t iterate over an instance, and getting one instance whole property is quite complicated when i searched it up. So i’ll just stick with the traditional way.

1 Like

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